import { useRef, useState } from 'react';
import {
  buildInstantFeedback,
  generateTriviaQuestion,
  generateTriviaQuestionWithHistory,
  getUserFacingErrorMessage,
  TriviaQuestion,
} from '../services/gemini';
import { Loader2, Play } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';

const PERSONALITIES = [
  { id: 'game-show', name: 'Classic Game Show Host' },
  { id: 'sarcastic', name: 'Sarcastic Robot' },
  { id: 'pirate', name: 'Salty Pirate' },
  { id: 'posh', name: 'Posh Aristocrat' },
  { id: 'hype', name: 'Hype Beast' },
];

export function ClassicTrivia() {
  const [topic, setTopic] = useState('Space Exploration');
  const [personality, setPersonality] = useState(PERSONALITIES[0]);
  const [loading, setLoading] = useState(false);
  const [questionData, setQuestionData] = useState<TriviaQuestion | null>(null);
  const [selectedAnswer, setSelectedAnswer] = useState<string | null>(null);
  const [feedback, setFeedback] = useState<string | null>(null);
  const [warningMessage, setWarningMessage] = useState<string | null>(null);
  const [questionHistory, setQuestionHistory] = useState<Record<string, string[]>>({});
  const lastFeedbackRef = useRef<string | null>(null);

  const sanitizeFeedback = (rawFeedback: string, personalityName: string) => {
    let text = rawFeedback.trim().replace(/^["']|["']$/g, '');
    const escapedPersonality = personalityName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    text = text.replace(new RegExp(`^${escapedPersonality}[^.!?]*[.!?]\\s*`, 'i'), '');
    text = text.replace(/^[A-Z][A-Za-z\s'-]+:\s*/, '');
    return text.trim() || rawFeedback.trim();
  };

  const historyKey = `${topic.trim().toLowerCase()}::${personality.id}`;

  const handleGenerate = async () => {
    setLoading(true);
    setQuestionData(null);
    setSelectedAnswer(null);
    setFeedback(null);
    setWarningMessage(null);
    lastFeedbackRef.current = null;
    
    try {
      const excludeQuestions = questionHistory[historyKey] ?? [];
      const data = excludeQuestions.length
        ? await generateTriviaQuestionWithHistory(topic, personality.name, excludeQuestions)
        : await generateTriviaQuestion(topic, personality.name);
      setQuestionData(data);
      setQuestionHistory((current) => {
        const existing = current[historyKey] ?? [];
        const next = [data.question, ...existing.filter((item) => item !== data.question)].slice(0, 6);
        return { ...current, [historyKey]: next };
      });
    } catch (error) {
      console.warn(error);
      setWarningMessage(
        getUserFacingErrorMessage(error, {
          requestType: 'Question generation',
          model: 'gemini-2.5-flash / gemini-2.5-flash-lite / OpenRouter',
        }),
      );
    } finally {
      setLoading(false);
    }
  };

  const handleAnswer = async (answer: string) => {
    if (selectedAnswer) return;
    setSelectedAnswer(answer);
    setWarningMessage(null);
    const responseText = buildInstantFeedback(
      questionData!.correctAnswer,
      answer,
      personality.name,
      lastFeedbackRef.current ?? undefined,
    );
    const cleanedFeedback = sanitizeFeedback(responseText, personality.name);
    lastFeedbackRef.current = cleanedFeedback;
    setFeedback(cleanedFeedback);
  };

  return (
    <div className="max-w-2xl mx-auto space-y-8">
      <div className="bg-slate-900 rounded-2xl p-6 border border-slate-800 shadow-xl">
        <h2 className="text-xl font-semibold mb-4 text-slate-200">Game Setup</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="block text-sm font-medium text-slate-400 mb-1">Topic</label>
            <input 
              type="text" 
              value={topic}
              onChange={(e) => setTopic(e.target.value)}
              className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2 text-slate-200 focus:outline-none focus:ring-2 focus:ring-indigo-500"
              placeholder="e.g. 90s Pop Music"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-400 mb-1">Host Personality</label>
            <select 
              value={personality.id}
              onChange={(e) => setPersonality(PERSONALITIES.find(p => p.id === e.target.value)!)}
              className="w-full bg-slate-950 border border-slate-800 rounded-xl px-4 py-2 text-slate-200 focus:outline-none focus:ring-2 focus:ring-indigo-500"
            >
              {PERSONALITIES.map(p => (
                <option key={p.id} value={p.id}>{p.name}</option>
              ))}
            </select>
          </div>
        </div>
        <button 
          onClick={handleGenerate}
          disabled={loading && !questionData}
          className="mt-6 w-full bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-3 rounded-xl transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
        >
          {loading && !questionData ? <Loader2 className="w-5 h-5 animate-spin" /> : <Play className="w-5 h-5" />}
          Generate Question
        </button>

        {!questionData && warningMessage && (
          <div className="mt-4 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-100">
            {warningMessage}
          </div>
        )}
      </div>

      <AnimatePresence mode="wait">
        {questionData && (
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className="bg-slate-900 rounded-2xl p-6 border border-slate-800 shadow-xl"
          >
            <div className="mb-6">
              <p className="text-indigo-400 font-medium mb-1">{personality.name}</p>
              <p className="text-slate-300 italic mb-4">"{questionData.hostCommentary}"</p>
              {questionData.providerMessage && (
                <div className="mb-4 rounded-xl border border-sky-500/20 bg-sky-500/10 px-3 py-2 text-xs font-medium text-sky-100">
                  {questionData.providerMessage}
                </div>
              )}
              <div className="min-h-[5.5rem]">
                <h3 className="text-3xl font-semibold leading-tight text-white whitespace-pre-wrap">
                  {questionData.question}
                </h3>
              </div>
            </div>

            <div className="grid gap-3 sm:grid-cols-2">
              {questionData.options.map((opt, i) => {
                const isSelected = selectedAnswer === opt;
                const isCorrect = opt === questionData.correctAnswer;
                const showResult = selectedAnswer !== null;
                
                let btnClass = "bg-slate-800 hover:bg-slate-700 border-slate-700 text-slate-200";
                if (showResult) {
                  if (isCorrect) btnClass = "bg-emerald-900/50 border-emerald-500 text-emerald-200";
                  else if (isSelected) btnClass = "bg-rose-900/50 border-rose-500 text-rose-200";
                  else btnClass = "bg-slate-900 border-slate-800 text-slate-500 opacity-50";
                }

                return (
                  <button
                    key={i}
                    onClick={() => handleAnswer(opt)}
                    disabled={showResult || loading}
                    className={`p-4 rounded-xl border text-left transition-all ${btnClass}`}
                  >
                    {opt}
                  </button>
                );
              })}
            </div>

            {feedback && (
              <motion.div 
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                className="mt-6 p-4 rounded-xl bg-slate-950 border border-slate-800"
              >
                <p className="text-slate-300">{feedback}</p>
              </motion.div>
            )}

            {warningMessage && (
              <div className="mt-6 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-100">
                {warningMessage}
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
