"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import AnimatedSection from "@/components/AnimatedSection";
import { Clock, AlertCircle, Trophy } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { getStoredLanguage } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";

const examQuestions = [
  { id: 1, type: "MCQ", question: "Who is the speaker of the Bhagavad Gita?", options: ["Arjuna", "Krishna", "Vyasa", "Sanjaya"], correctAnswer: [1], marks: 1 },
  { id: 2, type: "MCQ", question: "How many chapters are there in the Bhagavad Gita?", options: ["16", "18", "20", "22"], correctAnswer: [1], marks: 1 },
];

export default function OlympiadExam() {
  const { toast } = useToast();
  const [started, setStarted] = useState(false);
  const [timeLeft, setTimeLeft] = useState(120 * 60);
  const [answers, setAnswers] = useState<{ [key: number]: number[] }>({});
  const [submitted, setSubmitted] = useState(false);
  const [score, setScore] = useState(0);
  const [rank, setRank] = useState(0);
  const lang = getStoredLanguage();
  const t = getTranslation(lang).olympiadExamPage;

  useEffect(() => {
    if (!started || submitted) return;
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          handleAutoSubmit();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [started, submitted]);

  const formatTime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
  };

  const handleMCQAnswer = (questionId: number, optionIndex: number) => {
    setAnswers({ ...answers, [questionId]: [optionIndex] });
  };

  const calculateScore = () => {
    let totalScore = 0;
    examQuestions.forEach((question) => {
      const userAnswer = answers[question.id] || [];
      if (userAnswer[0] === question.correctAnswer[0]) {
        totalScore += question.marks;
      }
    });
    return totalScore;
  };

  const handleAutoSubmit = () => {
    const finalScore = calculateScore();
    setScore(finalScore);
    setRank(Math.floor(Math.random() * 1000) + 1);
    setSubmitted(true);
    toast({ title: t.autoSubmittedTitle, description: t.autoSubmittedDescription });
  };

  const handleSubmit = () => {
    const unanswered = examQuestions.length - Object.keys(answers).length;
    if (unanswered > 0 && !confirm(`${t.submitConfirmPrefix} ${unanswered} ${t.submitConfirmSuffix}`)) return;
    const finalScore = calculateScore();
    setScore(finalScore);
    setRank(Math.floor(Math.random() * 1000) + 1);
    setSubmitted(true);
    toast({ title: t.submittedTitle, description: t.submittedDescription });
  };

  const totalMarks = examQuestions.reduce((acc, q) => acc + q.marks, 0);
  const percentage = (score / totalMarks) * 100;

  if (!started) {
    return (
      <div className="pt-20 min-h-screen bg-gradient-to-br from-orange-50 to-white">
        <div className="container mx-auto px-4 py-20">
          <AnimatedSection className="max-w-3xl mx-auto text-center">
            <Trophy className="w-20 h-20 text-[#FAA631] mx-auto mb-6" />
            <h1 className="text-5xl font-bold text-gray-900 mb-4">{t.title}</h1>
            <p className="text-xl text-gray-600 mb-8">{t.subtitle}</p>
            <Card className="p-8 text-left">
              <h2 className="text-2xl font-bold mb-6">{t.instructionsTitle}</h2>
              <ul className="space-y-3 mb-8">
                <li className="flex items-start space-x-3"><AlertCircle className="w-5 h-5 text-[#FAA631] mt-1 flex-shrink-0" /><span>{t.totalQuestions}: {examQuestions.length}</span></li>
                <li className="flex items-start space-x-3"><AlertCircle className="w-5 h-5 text-[#FAA631] mt-1 flex-shrink-0" /><span>{t.totalMarks}: {totalMarks}</span></li>
                <li className="flex items-start space-x-3"><AlertCircle className="w-5 h-5 text-[#FAA631] mt-1 flex-shrink-0" /><span>{t.duration}</span></li>
                <li className="flex items-start space-x-3"><AlertCircle className="w-5 h-5 text-[#FAA631] mt-1 flex-shrink-0" /><span>{t.autoSubmit}</span></li>
                <li className="flex items-start space-x-3"><AlertCircle className="w-5 h-5 text-[#FAA631] mt-1 flex-shrink-0" /><span>{t.randomized}</span></li>
                <li className="flex items-start space-x-3"><AlertCircle className="w-5 h-5 text-[#FAA631] mt-1 flex-shrink-0" /><span>{t.questionTypes}</span></li>
              </ul>
              <Button onClick={() => setStarted(true)} size="lg" className="w-full bg-[#FAA631] hover:bg-orange-400 text-lg py-6">{t.startExam}</Button>
            </Card>
          </AnimatedSection>
        </div>
      </div>
    );
  }

  if (submitted) {
    const passed = percentage >= 40;
    return (
      <div className="pt-20 min-h-screen bg-gradient-to-br from-orange-50 to-white">
        <div className="container mx-auto px-4 py-20">
          <AnimatedSection className="max-w-3xl mx-auto text-center">
            <Trophy className={`w-20 h-20 mx-auto mb-6 ${passed ? "text-green-600" : "text-[#FAA631]"}`} />
            <h1 className="text-5xl font-bold text-gray-900 mb-4">{passed ? t.congratulations : t.results}</h1>
            <Card className="p-8">
              <div className="text-center mb-8">
                <div className="text-7xl font-bold text-[#FAA631] mb-2">{score}/{totalMarks}</div>
                <p className="text-2xl text-gray-700">{percentage.toFixed(1)}% {t.scoreSuffix}</p>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div className="p-4 bg-orange-50 rounded-lg"><p className="text-sm text-gray-600">{t.yourScore}</p><p className="text-2xl font-bold text-gray-900">{score}</p></div>
                <div className="p-4 bg-orange-50 rounded-lg"><p className="text-sm text-gray-600">{t.yourRank}</p><p className="text-2xl font-bold text-gray-900">#{rank}</p></div>
                <div className="p-4 bg-orange-50 rounded-lg"><p className="text-sm text-gray-600">{t.status}</p><p className={`text-2xl font-bold ${passed ? "text-green-600" : "text-red-600"}`}>{passed ? t.passed : t.notPassed}</p></div>
              </div>
              {passed && <div className="bg-green-50 border-2 border-green-500 p-6 rounded-lg mb-6"><h3 className="text-xl font-bold text-green-900 mb-2">{t.certificateEligible}</h3><p className="text-green-700">{t.certificateDescription}</p></div>}
              <div className="flex flex-col sm:flex-row gap-4">
                <Button onClick={() => (window.location.href = "/olympiad/course")} variant="outline" className="flex-1 hover:bg-[#FAA631]">{t.reviewCourse}</Button>
                <Button onClick={() => (window.location.href = "/")} className="flex-1 bg-[#FAA631] hover:bg-orange-400">{t.goHome}</Button>
              </div>
            </Card>
          </AnimatedSection>
        </div>
      </div>
    );
  }

  return (
    <div className="pt-20 min-h-screen bg-gradient-to-br from-orange-50 to-white">
      <div className="sticky top-20 z-40 bg-white shadow-md">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-bold text-gray-900">{t.examHeader}</h2>
            <div className="flex items-center space-x-4">
              <div className={`flex items-center space-x-2 px-4 py-2 rounded-lg ${timeLeft < 300 ? "bg-red-100" : "bg-orange-100"}`}>
                <Clock className={`w-5 h-5 ${timeLeft < 300 ? "text-red-600" : "text-[#FAA631]"}`} />
                <span className={`font-mono text-lg font-bold ${timeLeft < 300 ? "text-red-600" : "text-[#FAA631]"}`}>{formatTime(timeLeft)}</span>
              </div>
              <Button onClick={handleSubmit} className="bg-green-600 hover:bg-green-700">{t.submitExam}</Button>
            </div>
          </div>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto space-y-6">
          {examQuestions.map((question, index) => (
            <Card key={question.id}>
              <CardHeader>
                <CardTitle className="flex items-start justify-between">
                  <span className="flex-grow"><span className="text-[#FAA631] mr-2">Q{index + 1}.</span>{question.question}</span>
                  <span className="text-sm font-normal text-gray-600 ml-4 flex-shrink-0">{question.marks} {question.marks === 1 ? t.mark : t.marks}</span>
                </CardTitle>
                <p className="text-sm text-gray-500">{t.singleCorrect}</p>
              </CardHeader>
              <CardContent>
                <RadioGroup value={answers[question.id]?.[0]?.toString()} onValueChange={(value) => handleMCQAnswer(question.id, parseInt(value))}>
                  <div className="space-y-3">
                    {question.options.map((option, optIndex) => (
                      <div key={optIndex} className="flex items-center space-x-3 p-3 rounded-lg border-2 hover:bg-orange-50 transition-colors cursor-pointer" onClick={() => handleMCQAnswer(question.id, optIndex)}>
                        <RadioGroupItem value={optIndex.toString()} id={`q${question.id}-opt${optIndex}`} />
                        <Label htmlFor={`q${question.id}-opt${optIndex}`} className="flex-grow cursor-pointer">{option}</Label>
                      </div>
                    ))}
                  </div>
                </RadioGroup>
              </CardContent>
            </Card>
          ))}

          <div className="sticky bottom-4 bg-white p-4 rounded-lg shadow-lg border-2 border-orange-200">
            <div className="flex items-center justify-between">
              <span className="text-gray-700">{t.answered}: {Object.keys(answers).length} / {examQuestions.length}</span>
              <Button onClick={handleSubmit} size="lg" className="bg-green-600 hover:bg-green-700">{t.submitExam}</Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
