"use client";

import { use, useState, useTransition, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { 
  Clock, 
  ChevronLeft, 
  ChevronRight, 
  Globe,
  GraduationCap,
  Flag,
  Award,
  Download
} from "lucide-react";
import { Button } from "@workspace/ui/components/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@workspace/ui/components/card";
import { Input } from "@workspace/ui/components/input";
import { Label } from "@workspace/ui/components/label";

import idMessages from "../../../../messages/id.json";
import enMessages from "../../../../messages/en.json";
import jaMessages from "../../../../messages/ja.json";
import koMessages from "../../../../messages/ko.json";

// Import data soal dari file JSON terpisah
import dynamicQuestionsPool from "./questionsData.json";

const dictionaries: Record<string, any> = {
  id: idMessages,
  en: enMessages,
  ja: jaMessages,
  ko: koMessages,
};

export default function QuizJftNextPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = use(params);
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  const [isMounted, setIsMounted] = useState(false);
  useEffect(() => {
    setIsMounted(true);
  }, []);

  const currentLocale = dictionaries[locale] ? locale : "id";

  const [screen, setScreen] = useState<'home' | 'quiz' | 'result'>('home');
  const [userName, setUserName] = useState('');
  const [selectedLanguage, setSelectedLanguage] = useState('ja');
  const [selectedExam, setSelectedExam] = useState('JFT (Japan Foundation Test)');
  const [selectedSubLevel, setSelectedSubLevel] = useState('JFT-A2');
  const [errorMessage, setErrorMessage] = useState('');

  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [userAnswers, setUserAnswers] = useState<Record<number, number>>({});
  const [flaggedQuestions, setFlaggedQuestions] = useState<Record<number, boolean>>({});
  const [expiredQuestions, setExpiredQuestions] = useState<Record<number, boolean>>({});
  const [score, setScore] = useState(0);
  const [examDate, setExamDate] = useState('');

  const activeQuestions = dynamicQuestionsPool[selectedSubLevel as keyof typeof dynamicQuestionsPool] || dynamicQuestionsPool["N5"] || [];
  const currentQ = activeQuestions[currentQuestionIndex];
  const questionDuration = currentQ?.duration || 15;
  const [timeLeft, setTimeLeft] = useState(questionDuration);

  // Ref untuk area sertifikat yang akan dicetak/di-download
  const certificateRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (screen !== 'quiz' || !currentQ) return;

    if (expiredQuestions[currentQuestionIndex]) {
      setTimeLeft(0);
      return;
    }

    setTimeLeft(currentQ.duration || 15);
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev > 1) return prev - 1;
        clearInterval(timer);
        setExpiredQuestions(exp => ({ ...exp, [currentQuestionIndex]: true }));
        
        if (currentQuestionIndex + 1 < activeQuestions.length) {
          setCurrentQuestionIndex(idx => idx + 1);
        }
        return 0;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [currentQuestionIndex, screen]);

  const handleLocaleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newLocale = e.target.value;
    startTransition(() => {
      router.push(`/${newLocale}/quiz-jft`);
    });
  };

  const handleStartQuiz = () => {
    if (!userName.trim()) {
      setErrorMessage('Masukkan nama lengkap terlebih dahulu!');
      return;
    }
    setErrorMessage('');
    setScreen('quiz');
    setCurrentQuestionIndex(0);
    setUserAnswers({});
    setFlaggedQuestions({});
    setExpiredQuestions({});
  };

  const handleSelectAnswer = (optIdx: number) => {
    if (expiredQuestions[currentQuestionIndex]) return;
    setUserAnswers(prev => ({ ...prev, [currentQuestionIndex]: optIdx }));
  };

  const toggleFlag = () => {
    if (expiredQuestions[currentQuestionIndex]) return;
    setFlaggedQuestions(prev => ({ ...prev, [currentQuestionIndex]: !prev[currentQuestionIndex] }));
  };

  const handleGoToQuestion = (idx: number) => {
    if (expiredQuestions[idx]) return;
    setCurrentQuestionIndex(idx);
  };

  const handleNextOrSubmit = () => {
    if (currentQuestionIndex + 1 < activeQuestions.length) {
      setCurrentQuestionIndex(prev => prev + 1);
    } else {
      handleSubmitQuiz();
    }
  };

  const handlePrevQuestion = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  const handleSubmitQuiz = () => {
    let correctCount = 0;
    activeQuestions.forEach((q: any, idx: number) => {
      if (userAnswers[idx] === q.c) {
        correctCount++;
      }
    });
    const calculatedScore = Math.round((correctCount / activeQuestions.length) * 100);
    setScore(calculatedScore);
    setExamDate(new Date().toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' }));
    setScreen('result');
  };

  const handleDownloadCertificate = () => {
    window.print();
  };

  const handleResetQuiz = () => {
    setScreen('home');
    setUserName('');
    setUserAnswers({});
    setFlaggedQuestions({});
    setExpiredQuestions({});
    setCurrentQuestionIndex(0);
    setScore(0);
  };

  if (!isMounted) return null;

  return (
    <div className="w-full max-w-7xl mx-auto p-0 overflow-x-hidden select-none font-sans bg-white min-h-screen text-black">
      
      {/* 1. HOME SCREEN */}
      {screen === 'home' && (
        <div className="p-4 bg-white min-h-screen flex items-center justify-center">
          <Card className="border-2 border-[#8cc63f] shadow-2xl rounded-none bg-white max-w-xl w-full text-black">
            <CardHeader className="text-center pb-2">
              <div className="flex justify-center mb-2">
                <GraduationCap className="w-12 h-12 text-[#689f2c]" />
              </div>
              <CardTitle className="text-xl font-bold text-[#689f2c]">Eduverse JFT / JLPT CBT Simulator</CardTitle>
              <CardDescription className="text-xs text-gray-500 mt-1">
                Pilih Ujian dan Masukkan Nama untuk Memulai
              </CardDescription>
            </CardHeader>

            <CardContent className="space-y-4 pt-4">
              {errorMessage && (
                <div className="bg-red-50 border-l-4 border-red-500 text-red-700 p-2 text-xs">
                  {errorMessage}
                </div>
              )}

              <div className="space-y-3">
                <div>
                  <Label className="text-xs font-bold mb-1 block">Pilih Bahasa</Label>
                  <select
                    value={selectedLanguage}
                    onChange={(e) => setSelectedLanguage(e.target.value)}
                    className="w-full border border-[#8cc63f] rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#689f2c] bg-white font-bold"
                  >
                    <option value="ja">🇯🇵 Bahasa Jepang (JLPT / JFT)</option>
                    <option value="ko">🇰🇷 Bahasa Korea (TOPIK)</option>
                    <option value="zh">🇨🇳 Bahasa Mandarin (HSK)</option>
                  </select>
                </div>

                <div>
                  <Label className="text-xs font-bold mb-1 block">Nama Lengkap</Label>
                  <Input 
                    value={userName}
                    onChange={(e) => setUserName(e.target.value)}
                    placeholder="Masukkan Nama Lengkap"
                    className="border-[#8cc63f] focus-visible:ring-[#689f2c] rounded-none"
                  />
                </div>

                <div>
                  <Label className="text-xs font-bold mb-1 block">Jenis Tes</Label>
                  <select
                    value={selectedExam}
                    onChange={(e) => {
                      setSelectedExam(e.target.value);
                      if (e.target.value.includes('JFT')) setSelectedSubLevel('JFT-A2');
                      else setSelectedSubLevel('N5');
                    }}
                    className="w-full border border-[#8cc63f] rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#689f2c] bg-white"
                  >
                    <option value="JFT (Japan Foundation Test)">JFT (Japan Foundation Test)</option>
                    <option value="JLPT (Bahasa Jepang)">JLPT (Bahasa Jepang)</option>
                  </select>
                </div>

                <div>
                  <Label className="text-xs font-bold mb-1 block">Sub Level</Label>
                  <select
                    value={selectedSubLevel}
                    onChange={(e) => setSelectedSubLevel(e.target.value)}
                    className="w-full border border-[#8cc63f] rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#689f2c] bg-white"
                  >
                    {selectedExam.includes('JFT') ? (
                      <option value="JFT-A2">A2 - JFT Basic</option>
                    ) : (
                      <>
                        <option value="N5">N5 (Dasar)</option>
                        <option value="N4">N4 (Dasar Lanjutan)</option>
                        <option value="N3">N3 (Menengah)</option>
                        <option value="N2">N2 (Menengah Atas)</option>
                        <option value="N1">N1 (Tingkat Lanjut)</option>
                      </>
                    )}
                  </select>
                </div>
              </div>

              <div className="pt-4">
                <Button 
                  onClick={handleStartQuiz}
                  className="bg-[#8cc63f] hover:bg-[#689f2c] text-white border-none w-full font-bold uppercase tracking-widest rounded-none shadow-md h-11 cursor-pointer"
                >
                  試験開始 (Mulai Ujian)
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 2. QUIZ SCREEN */}
      {screen === 'quiz' && currentQ && (
        <div className="w-full bg-white text-black min-h-[600px] flex flex-col justify-between font-sans border-b-2 border-black">
          
          <div className="bg-black text-white px-4 py-2 flex justify-between items-center text-sm">
            <div className="leading-tight">
              <div className="text-xs sm:text-sm font-semibold">Question: {currentQuestionIndex + 1}</div>
              <div className="text-xs sm:text-sm font-bold">Section: {currentQ.section_name}</div>
            </div>
            
            <div className="flex items-center space-x-2">
              <div className="bg-emerald-600 text-white px-2 py-1 rounded font-bold text-xs">EV</div>
              <span className="font-bold tracking-wider text-xs sm:text-sm">EDUVERSE BY ASLANASILON</span>
            </div>

            <div>
              <button 
                onClick={handleSubmitQuiz} 
                className="bg-[#f2ca65] hover:bg-[#e0b753] text-black font-bold px-6 py-1 rounded-sm text-xs sm:text-sm transition-colors border-none cursor-pointer"
              >
                finish
              </button>
            </div>
          </div>

          <div className="bg-[#8cc63f] text-white px-4 py-1 text-xs sm:text-sm font-bold flex justify-between items-center">
            <span>Test: {selectedExam} ({selectedSubLevel}) - Candidate: {userName}</span>
            <div className="flex items-center gap-1">
              <Globe className="w-3.5 h-3.5 text-white" />
              <select
                value={currentLocale}
                onChange={handleLocaleChange}
                disabled={isPending}
                className="text-xs bg-transparent text-white font-bold cursor-pointer focus:outline-none"
              >
                <option value="id" className="text-black">ID</option>
                <option value="en" className="text-black">EN</option>
                <option value="ja" className="text-black">JA</option>
                <option value="ko" className="text-black">KO</option>
              </select>
            </div>
          </div>

          <div className="p-4 sm:p-6 flex-1 flex flex-col justify-between bg-white">
            
            {currentQ.instruction && (
              <div className="bg-[#eef5fc] border-l-4 border-[#8cbbe8] text-[#2c3e50] px-4 py-2 text-xs sm:text-base mb-4 font-normal">
                {currentQ.instruction}
                {expiredQuestions[currentQuestionIndex] && (
                  <span className="ml-3 text-red-600 font-bold text-xs">[ Waktu Habis: Soal Terkunci ]</span>
                )}
              </div>
            )}

            <div className="grid grid-cols-12 gap-4 items-start flex-1 my-2">
              
              <div className="col-span-2 sm:col-span-1 space-y-1.5 pr-1">
                {activeQuestions.map((_: any, idx: number) => {
                  const isAnswered = userAnswers[idx] !== undefined;
                  const isCurrent = currentQuestionIndex === idx;
                  const isExpired = expiredQuestions[idx];
                  const isFlagged = flaggedQuestions[idx];

                  let btnStyle = "bg-[#a3d35c] text-white";
                  if (isCurrent) btnStyle = "bg-[#8cc63f] text-white font-bold ring-2 ring-black";
                  else if (isAnswered) btnStyle = "bg-[#7ab82e] text-white";
                  if (isExpired) btnStyle = "bg-gray-400 text-gray-700 cursor-not-allowed opacity-60";

                  return (
                    <button 
                      key={idx}
                      onClick={() => handleGoToQuestion(idx)}
                      disabled={isExpired}
                      className={`w-full text-center py-1 text-xs sm:text-sm font-bold border border-[#8cc63f] transition-all relative cursor-pointer ${btnStyle}`}
                      title={isExpired ? "Durasi habis, tidak bisa dibuka" : `Soal ${idx + 1}`}
                    >
                      {idx + 1}
                      {isFlagged && !isExpired && (
                        <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-amber-500 rounded-full border border-black" />
                      )}
                    </button>
                  );
                })}
              </div>

              <div className="col-span-10 sm:col-span-11 grid grid-cols-1 lg:grid-cols-12 gap-6 items-center pl-2">
                
                <div className="lg:col-span-5 flex flex-col justify-center">
                  {currentQ.passage && (
                    <div className="p-3 bg-gray-50 border border-gray-300 rounded text-xs sm:text-sm w-full mb-2 font-semibold">
                      {currentQ.passage}
                    </div>
                  )}
                  <div className="text-base sm:text-lg font-bold text-gray-800">
                    {currentQ.q}
                  </div>
                </div>

                <div className="lg:col-span-4 space-y-3 w-full">
                  {currentQ.a.map((optText: string, optIdx: number) => {
                    const isSelected = userAnswers[currentQuestionIndex] === optIdx;
                    const isDisabled = expiredQuestions[currentQuestionIndex];

                    return (
                      <button
                        key={optIdx}
                        type="button"
                        disabled={isDisabled}
                        onClick={() => handleSelectAnswer(optIdx)}
                        className={`w-full text-left px-3 py-2.5 border-2 border-black transition-all flex items-center gap-2 bg-white text-black text-base sm:text-lg font-medium rounded-none ${
                          isDisabled ? 'cursor-not-allowed opacity-70 bg-gray-50' : 'cursor-pointer hover:bg-gray-50'
                        } ${isSelected ? 'bg-blue-50 font-bold border-blue-800 ring-2 ring-blue-600' : ''}`}
                      >
                        <span className="font-bold text-lg min-w-[28px]">{String.fromCharCode(65 + optIdx)}.</span>
                        <span className="tracking-wide">{optText}</span>
                      </button>
                    );
                  })}
                </div>

                <div className="lg:col-span-3 flex flex-col items-center justify-center text-center my-4 lg:my-0 space-y-3">
                  <div>
                    <span className="text-xs sm:text-sm font-semibold text-black mb-1 block">
                      Answer in <span className="font-bold text-red-600">{timeLeft}</span> Seconds!
                    </span>
                    
                    <div className="relative w-16 h-16 sm:w-20 sm:h-20 flex items-center justify-center mx-auto">
                      <svg className="w-full h-full -rotate-90 transform" viewBox="0 0 36 36">
                        <path className="text-gray-200" strokeWidth="3.5" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
                        <path 
                          className="text-[#103d75] transition-all duration-1000 ease-linear" 
                          strokeWidth="18" 
                          strokeDasharray={`${(timeLeft / questionDuration) * 100}, 100`} 
                          stroke="currentColor" 
                          fill="none" 
                          d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" 
                        />
                      </svg>
                    </div>
                  </div>

                  <Button
                    onClick={toggleFlag}
                    disabled={expiredQuestions[currentQuestionIndex]}
                    variant={flaggedQuestions[currentQuestionIndex] ? "default" : "outline"}
                    className={`text-xs gap-1.5 h-8 w-full rounded-none ${
                      flaggedQuestions[currentQuestionIndex] 
                        ? 'bg-amber-500 hover:bg-amber-600 text-black font-bold' 
                        : 'border-black text-black hover:bg-gray-100'
                    }`}
                  >
                    <Flag className="w-3.5 h-3.5" />
                    {flaggedQuestions[currentQuestionIndex] ? "Ragu-ragu (Ditandai)" : "Tandai Ragu-ragu"}
                  </Button>
                </div>

              </div>
            </div>

            <div className="mt-8 pt-2 flex justify-between items-end bg-white border-t border-gray-100">
              <div className="flex flex-col text-[10px] sm:text-xs leading-tight font-sans text-gray-500">
                <span className="font-bold text-gray-600">JAPAN FOUNDATION / EDUVERSE</span>
                <span className="font-black text-purple-900 text-xs">CBT Simulator Engine</span>
              </div>

              <div className="flex items-center gap-2">
                <Button 
                  onClick={handlePrevQuestion}
                  disabled={currentQuestionIndex === 0}
                  className="bg-[#8cc63f] hover:bg-[#7ab82e] disabled:opacity-40 text-white font-bold px-4 py-1 text-xs sm:text-sm rounded-none border-none shadow-none cursor-pointer"
                >
                  <ChevronLeft className="w-4 h-4 mr-1" /> Back
                </Button>

                <Button 
                  onClick={handleNextOrSubmit}
                  className="bg-[#8cc63f] hover:bg-[#7ab82e] text-white font-bold px-4 py-1 text-xs sm:text-sm rounded-none border-none shadow-none cursor-pointer"
                >
                  {currentQuestionIndex + 1 === activeQuestions.length ? 'Finish' : 'Next'} <ChevronRight className="w-4 h-4 ml-1" />
                </Button>
              </div>
            </div>

          </div>
        </div>
      )}

      {/* 3. RESULT SCREEN & SERTIFIKAT KELULUSAN */}
      {screen === 'result' && (
        <div className="p-4 bg-gray-100 min-h-screen flex flex-col items-center justify-center space-y-6">
          
          <div 
            ref={certificateRef}
            className="w-full max-w-3xl bg-white border-8 border-[#8cc63f] p-8 sm:p-12 text-center shadow-2xl relative font-serif text-black"
          >
            <div className="flex justify-between items-center border-b-2 border-gray-200 pb-4 mb-6">
              <div className="flex items-center gap-2">
                <div className="bg-[#8cc63f] text-white p-2 font-bold text-sm">EV</div>
                <span className="font-sans font-bold text-sm tracking-widest text-gray-700">EDUVERSE BY ASLANASILON</span>
              </div>
              <span className="font-sans text-xs text-gray-500">Certificate No: EV-CERT-{Math.floor(100000 + Math.random() * 900000)}</span>
            </div>

            <div className="space-y-4 my-6">
              <h3 className="font-sans text-xs uppercase tracking-widest text-[#689f2c] font-bold">Sertifikat Kelulusan Resmi</h3>
              <h1 className="text-3xl sm:text-4xl font-bold tracking-wide text-gray-900">Certificate of Completion</h1>
              <p className="font-sans text-xs sm:text-sm text-gray-500">Sertifikat ini diberikan dengan bangga kepada:</p>
              
              <div className="text-2xl sm:text-3xl font-bold text-[#689f2c] border-b-2 border-dashed border-[#8cc63f] inline-block px-8 py-1 my-2">
                {userName}
              </div>

              <p className="font-sans text-xs sm:text-sm text-gray-600 max-w-lg mx-auto leading-relaxed">
                Atas keberhasilannya menyelesaikan simulasi ujian <strong className="text-black">{selectedExam}</strong> untuk level <strong className="text-black">{selectedSubLevel}</strong> dengan pencapaian nilai akhir:
              </p>

              <div className="inline-block bg-emerald-50 border border-[#8cc63f] px-6 py-3 my-2">
                <span className="font-sans text-[10px] uppercase font-bold text-emerald-800 tracking-wider block">Total Skor Ujian</span>
                <div className="font-sans text-4xl font-black text-[#689f2c]">{score} <span className="text-lg font-normal text-gray-600">/ 100</span></div>
              </div>
            </div>

            <div className="flex justify-between items-end pt-12 mt-8 border-t-2 border-gray-200 text-xs font-sans">
              <div className="text-left text-gray-500">
                <p>Tanggal Ujian: <strong className="text-black">{examDate}</strong></p>
                <p>Status: <strong className={score >= 60 ? "text-green-600" : "text-amber-600"}>{score >= 60 ? "LULUS (PASSED)" : "BELUM LULUS"}</strong></p>
              </div>
              <div className="text-center">
                <div className="font-serif italic text-lg font-bold text-gray-800 mb-1">Aslan Asilon</div>
                <div className="border-t border-black pt-1 px-4 font-bold text-gray-700">Director of Eduverse</div>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-4">
            <Button 
              onClick={handleDownloadCertificate}
              className="bg-blue-600 hover:bg-blue-700 text-white font-bold px-6 py-2 rounded-none gap-2 shadow-lg cursor-pointer"
            >
              <Download className="w-4 h-4" /> Download / Print Certificate
            </Button>

            <Button 
              onClick={handleResetQuiz}
              className="bg-[#8cc63f] hover:bg-[#689f2c] text-white font-bold px-6 py-2 rounded-none gap-2 shadow-lg cursor-pointer"
            >
              <Award className="w-4 h-4" /> Ulangi Ujian / Menu Utama
            </Button>
          </div>

        </div>
      )}

    </div>
  );
}