// (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)

import { useState } from 'react';
import { Clock, Database, Send } from 'lucide-react';
import { useTranslation } from '@/i18n/TranslationProvider';
import { usePlaygroundAsk } from '../hooks/usePlaygroundAsk';
import { PlaygroundSourceRow } from './PlaygroundSourceRow';

interface PlaygroundTabProps {
  tenantId: string;
}

/**
 * Top-level container for the Knowledge Playground tab. Owns the question
 * input, fires the ask mutation, and renders the answer + sources.
 * Sub-components handle individual source rows and chunk editing.
 */
export function PlaygroundTab({ tenantId }: PlaygroundTabProps) {
  const { t } = useTranslation();
  const [question, setQuestion] = useState<string>('');
  const askMutation = usePlaygroundAsk(tenantId);

  const disabled = askMutation.isPending || question.trim().length === 0;

  const handleAsk = () => {
    askMutation.mutate({ question, topK: 8 });
  };

  const handleAskAgain = () => {
    if (question.trim().length > 0) {
      askMutation.mutate({ question, topK: 8 });
    }
  };

  const answer = askMutation.data;

  return (
    <div className="p-4 space-y-4">
      {/* Question input */}
      <div className="bg-white border border-gray-200 rounded-lg p-3 shadow-sm">
        <textarea
          value={question}
          onChange={(e) => setQuestion(e.target.value)}
          placeholder={t('knowledge.playground.questionPlaceholder')}
          maxLength={2000}
          className="w-full min-h-[80px] px-3 py-2 text-sm text-gray-900 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent"
        />
        <div className="mt-2 flex items-center justify-between">
          <span className="text-xs text-gray-400">{question.length} / 2000</span>
          <button
            onClick={handleAsk}
            disabled={disabled}
            className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-cyan-600 rounded-lg hover:bg-cyan-700 disabled:bg-cyan-300 disabled:cursor-not-allowed transition-colors"
          >
            <Send size={14} />
            {askMutation.isPending
              ? t('knowledge.playground.thinking')
              : t('knowledge.playground.ask')}
          </button>
        </div>
      </div>

      {/* Error banner */}
      {askMutation.error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-800">
          <p className="font-medium">{t('knowledge.playground.error')}</p>
          <p className="text-xs mt-1 opacity-80">{askMutation.error.message}</p>
        </div>
      )}

      {/* Answer card */}
      {answer && (
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 space-y-3">
          <div className="flex items-center gap-3 text-xs text-gray-500">
            <span className="inline-flex items-center gap-1">
              <Clock size={12} />
              {answer.metrics.ms} ms
            </span>
            <span className="inline-flex items-center gap-1">
              <Database size={12} />
              {answer.metrics.hits} {t('knowledge.playground.metricsHitsSuffix')}
            </span>
          </div>
          <p className="text-sm text-gray-900 whitespace-pre-wrap">{answer.answer}</p>
        </div>
      )}

      {/* Sources */}
      {answer && (
        <div className="space-y-2">
          <h3 className="text-sm font-semibold text-gray-700">
            {t('knowledge.playground.sourcesTitle')}{' '}
            <span className="text-gray-400 font-normal">({answer.sources.length})</span>
          </h3>
          {answer.sources.length === 0 ? (
            <p className="text-sm text-gray-500 italic">{t('knowledge.playground.noSources')}</p>
          ) : (
            answer.sources.map((source, idx) => (
              <PlaygroundSourceRow
                key={source.pointId}
                tenantId={tenantId}
                source={source}
                rank={idx + 1}
                onChange={handleAskAgain}
              />
            ))
          )}
        </div>
      )}
    </div>
  );
}
