import React from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { 
  MessageSquare, Send, CheckCircle2, AlertCircle, 
  ArrowRight, Trophy, Brain, Target, RefreshCw, 
  ChevronRight, Sparkles, User, Award
} from 'lucide-react';
import { VivaQuestion, VivaEvaluation, VivaSession, UserProgress } from '../types';
import { generateVivaQuestions, evaluateVivaAnswer, generateVivaSummary } from '../lib/vivaSimulator';
import { cn } from '../lib/utils';

interface VivaSimulatorProps {
  progress: UserProgress;
  level: number;
  onComplete: (session: VivaSession) => void;
  onClose: () => void;
}

export function VivaSimulator({ progress, level, onComplete, onClose }: VivaSimulatorProps) {
  const [step, setStep] = React.useState<'start' | 'questioning' | 'feedback' | 'summary'>('start');
  const [questions, setQuestions] = React.useState<VivaQuestion[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = React.useState(0);
  const [answer, setAnswer] = React.useState('');
  const [isEvaluating, setIsEvaluating] = React.useState(false);
  const [lastEvaluation, setLastEvaluation] = React.useState<VivaEvaluation | null>(null);
  const [session, setSession] = React.useState<Partial<VivaSession>>({
    id: Date.now().toString(),
    level,
    language: progress.language || 'JavaScript',
    questions: []
  });
  const [loading, setLoading] = React.useState(false);

  const startViva = async () => {
    setLoading(true);
    try {
      const qs = await generateVivaQuestions(progress, level, 5);
      setQuestions(qs);
      setStep('questioning');
    } catch (error) {
      console.error("Failed to start viva:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmitAnswer = async () => {
    if (!answer.trim() || isEvaluating) return;
    
    setIsEvaluating(true);
    try {
      const evaluation = await evaluateVivaAnswer(
        questions[currentQuestionIndex],
        answer,
        progress.language || 'JavaScript'
      );
      
      setLastEvaluation(evaluation);
      setSession(prev => ({
        ...prev,
        questions: [
          ...(prev.questions || []),
          {
            question: questions[currentQuestionIndex],
            answer,
            evaluation
          }
        ]
      }));
      
      setStep('feedback');
    } catch (error) {
      console.error("Failed to evaluate answer:", error);
    } finally {
      setIsEvaluating(false);
    }
  };

  const nextQuestion = async () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(prev => prev + 1);
      setAnswer('');
      setLastEvaluation(null);
      setStep('questioning');
    } else {
      setLoading(true);
      try {
        const summary = await generateVivaSummary(session);
        const finalSession: VivaSession = {
          ...session as VivaSession,
          summary,
          completedAt: new Date().toISOString()
        };
        setSession(finalSession);
        setStep('summary');
      } catch (error) {
        console.error("Failed to generate summary:", error);
      } finally {
        setLoading(false);
      }
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/90 backdrop-blur-sm">
      <motion.div 
        initial={{ opacity: 0, scale: 0.95, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        className="bg-dark-card w-full max-w-2xl rounded-3xl border border-dark-border shadow-2xl overflow-hidden flex flex-col max-h-[90vh]"
      >
        {/* Header */}
        <div className="p-6 border-b border-dark-border flex items-center justify-between bg-dark-card/50">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-[#0b8c9f]/10 rounded-xl flex items-center justify-center text-[#0b8c9f]">
              <MessageSquare size={20} />
            </div>
            <div>
              <h3 className="text-xl font-black text-white">AI Viva Simulator</h3>
              <p className="text-xs text-slate-400 font-bold uppercase tracking-widest">Level {level} • {progress.language}</p>
            </div>
          </div>
          <button 
            onClick={onClose}
            className="text-slate-500 hover:text-white transition-colors"
          >
            <AlertCircle size={24} />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
          <AnimatePresence mode="wait">
            {step === 'start' && (
              <motion.div 
                key="start"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="text-center space-y-8 py-8"
              >
                <div className="w-20 h-20 bg-[#0b8c9f]/10 rounded-3xl flex items-center justify-center text-[#0b8c9f] mx-auto">
                  <Brain size={40} />
                </div>
                <div>
                  <h4 className="text-2xl font-black text-white mb-2">Ready for your Viva?</h4>
                  <p className="text-slate-400 max-w-md mx-auto">
                    I'll ask you 5 questions about what you've learned. Practice explaining your logic clearly and confidently!
                  </p>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 max-w-lg mx-auto">
                  {[
                    { icon: Target, label: "Conceptual Clarity" },
                    { icon: MessageSquare, label: "Logical Explanation" },
                    { icon: Award, label: "Confidence Building" }
                  ].map((item, i) => (
                    <div key={i} className="p-4 bg-slate-900/50 rounded-2xl border border-dark-border">
                      <item.icon className="mx-auto mb-2 text-[#0b8c9f]" size={20} />
                      <div className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">{item.label}</div>
                    </div>
                  ))}
                </div>
                <button 
                  onClick={startViva}
                  disabled={loading}
                  className="bg-[#0b8c9f] hover:bg-[#0b8c9f]/90 text-white px-8 py-4 rounded-2xl font-black shadow-lg shadow-[#0b8c9f]/20 transition-all flex items-center gap-2 mx-auto disabled:opacity-50"
                >
                  {loading ? <RefreshCw className="animate-spin" /> : <Sparkles size={20} />}
                  Start Viva Session
                </button>
              </motion.div>
            )}

            {step === 'questioning' && (
              <motion.div 
                key="questioning"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                className="space-y-8"
              >
                {/* Progress */}
                <div className="flex items-center justify-between">
                  <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Question {currentQuestionIndex + 1} of {questions.length}</div>
                  <div className="flex gap-1">
                    {questions.map((_, i) => (
                      <div 
                        key={i} 
                        className={cn(
                          "h-1.5 rounded-full transition-all duration-500",
                          i === currentQuestionIndex ? "w-8 bg-[#0b8c9f]" : 
                          i < currentQuestionIndex ? "w-4 bg-green-500/50" : "w-4 bg-slate-800"
                        )}
                      />
                    ))}
                  </div>
                </div>

                {/* Question */}
                <div className="bg-slate-900/50 p-8 rounded-3xl border border-dark-border relative overflow-hidden">
                  <div className="absolute top-0 left-0 w-1 h-full bg-[#0b8c9f]" />
                  <div className="flex items-center gap-2 mb-4">
                    <span className="px-2 py-1 bg-[#0b8c9f]/10 text-[#0b8c9f] text-[10px] font-bold rounded uppercase tracking-widest">
                      {questions[currentQuestionIndex].type}
                    </span>
                  </div>
                  <h4 className="text-xl font-bold text-white leading-relaxed">
                    {questions[currentQuestionIndex].text}
                  </h4>
                  {questions[currentQuestionIndex].context && (
                    <div className="mt-6 p-4 bg-slate-950 rounded-xl border border-dark-border font-mono text-sm text-slate-300 overflow-x-auto">
                      <pre>{questions[currentQuestionIndex].context}</pre>
                    </div>
                  )}
                </div>

                {/* Answer Input */}
                <div className="space-y-4">
                  <div className="text-xs font-bold text-slate-500 uppercase tracking-widest">Your Explanation</div>
                  <textarea 
                    value={answer}
                    onChange={(e) => setAnswer(e.target.value)}
                    placeholder="Type your answer here... Be as descriptive as possible!"
                    className="w-full h-32 bg-slate-900 border border-dark-border rounded-2xl p-4 text-white placeholder:text-slate-600 focus:outline-none focus:border-[#0b8c9f] transition-colors resize-none custom-scrollbar"
                  />
                  <button 
                    onClick={handleSubmitAnswer}
                    disabled={!answer.trim() || isEvaluating}
                    className="w-full bg-[#0b8c9f] hover:bg-[#0b8c9f]/90 text-white py-4 rounded-2xl font-black shadow-lg shadow-[#0b8c9f]/20 transition-all flex items-center justify-center gap-2 disabled:opacity-50"
                  >
                    {isEvaluating ? <RefreshCw className="animate-spin" /> : <Send size={20} />}
                    Submit Answer
                  </button>
                </div>
              </motion.div>
            )}

            {step === 'feedback' && lastEvaluation && (
              <motion.div 
                key="feedback"
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                className="space-y-8"
              >
                <div className="text-center">
                  <div className={cn(
                    "w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg",
                    lastEvaluation.isCorrect ? "bg-green-500/10 text-green-500 shadow-green-500/10" : "bg-orange-500/10 text-orange-500 shadow-orange-500/10"
                  )}>
                    {lastEvaluation.isCorrect ? <CheckCircle2 size={32} /> : <Brain size={32} />}
                  </div>
                  <h4 className="text-xl font-black text-white">{lastEvaluation.qualitativeScore}</h4>
                </div>

                <div className="space-y-4">
                  <div className="p-6 bg-green-500/5 rounded-2xl border border-green-500/20">
                    <div className="text-[10px] font-bold text-green-500 uppercase tracking-widest mb-2">What was correct</div>
                    <p className="text-sm text-slate-300 leading-relaxed">{lastEvaluation.feedback.correct}</p>
                  </div>
                  <div className="p-6 bg-orange-500/5 rounded-2xl border border-orange-500/20">
                    <div className="text-[10px] font-bold text-orange-500 uppercase tracking-widest mb-2">What was missing</div>
                    <p className="text-sm text-slate-300 leading-relaxed">{lastEvaluation.feedback.missing}</p>
                  </div>
                  <div className="p-6 bg-[#0b8c9f]/5 rounded-2xl border border-[#0b8c9f]/20">
                    <div className="text-[10px] font-bold text-[#0b8c9f] uppercase tracking-widest mb-2">How to improve</div>
                    <p className="text-sm text-slate-300 leading-relaxed">{lastEvaluation.feedback.improvement}</p>
                  </div>
                </div>

                <button 
                  onClick={nextQuestion}
                  className="w-full bg-slate-800 hover:bg-slate-700 text-white py-4 rounded-2xl font-black transition-all flex items-center justify-center gap-2"
                >
                  {currentQuestionIndex < questions.length - 1 ? "Next Question" : "View Final Summary"}
                  <ArrowRight size={20} />
                </button>
              </motion.div>
            )}

            {step === 'summary' && session.summary && (
              <motion.div 
                key="summary"
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="space-y-8 py-4"
              >
                <div className="text-center">
                  <div className="w-20 h-20 bg-yellow-500/10 rounded-3xl flex items-center justify-center text-yellow-500 mx-auto mb-6 shadow-xl shadow-yellow-500/10">
                    <Trophy size={40} />
                  </div>
                  <h4 className="text-3xl font-black text-white mb-2">Viva Completed!</h4>
                  <div className="inline-block px-4 py-1.5 bg-yellow-500/10 text-yellow-500 rounded-full text-sm font-black uppercase tracking-widest border border-yellow-500/20">
                    {session.summary.finalQualitative}
                  </div>
                </div>

                <div className="bg-slate-900/50 p-8 rounded-3xl border border-dark-border">
                  <div className="text-xs font-bold text-slate-500 uppercase tracking-widest mb-4">Overall Performance</div>
                  <p className="text-slate-300 leading-relaxed italic">"{session.summary.overall}"</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="p-6 bg-green-500/5 rounded-2xl border border-green-500/20">
                    <div className="text-[10px] font-bold text-green-500 uppercase tracking-widest mb-4 flex items-center gap-2">
                      <Award size={14} /> Key Strengths
                    </div>
                    <ul className="space-y-3">
                      {session.summary.strengths.map((s, i) => (
                        <li key={i} className="flex items-start gap-2 text-xs text-slate-300">
                          <CheckCircle2 size={14} className="text-green-500 mt-0.5 flex-shrink-0" />
                          {s}
                        </li>
                      ))}
                    </ul>
                  </div>
                  <div className="p-6 bg-orange-500/5 rounded-2xl border border-orange-500/20">
                    <div className="text-[10px] font-bold text-orange-500 uppercase tracking-widest mb-4 flex items-center gap-2">
                      <Target size={14} /> Areas to Improve
                    </div>
                    <ul className="space-y-3">
                      {session.summary.improvements.map((s, i) => (
                        <li key={i} className="flex items-start gap-2 text-xs text-slate-300">
                          <ChevronRight size={14} className="text-orange-500 mt-0.5 flex-shrink-0" />
                          {s}
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>

                <button 
                  onClick={() => onComplete(session as VivaSession)}
                  className="w-full bg-[#0b8c9f] hover:bg-[#0b8c9f]/90 text-white py-4 rounded-2xl font-black shadow-lg shadow-[#0b8c9f]/20 transition-all"
                >
                  Save & Finish Session
                </button>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </motion.div>
    </div>
  );
}
