"use client";

import React, { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Clock, ChevronLeft, ChevronRight, Bookmark, X } from "lucide-react";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";

interface Props {
  testData: any;
  answers: number[];
  setAnswers: React.Dispatch<React.SetStateAction<number[]>>;
  currentQuestion: number;
  setCurrentQuestion: React.Dispatch<React.SetStateAction<number>>;
  marked: boolean[];
  setMarked: React.Dispatch<React.SetStateAction<boolean[]>>;
  timeLeft: number;
  formatTime: (s: number) => string;
  next: () => void;
  prev: () => void;
  score: () => number;
  showResults: boolean;
  showSolution: boolean;
  setShowSolution: (v: boolean) => void;
  confirmSubmit: boolean;
  setConfirmSubmit: (v: boolean) => void;
  saveTest: () => Promise<void>;
  getTestResultdata: () => Promise<void>;
  exitFullscreen: () => void;
  totalDuration: number;
  setTimeTaken: (v: number) => void;
  scrollToTop: () => void;

  /* 🔴 REQUIRED BUT MISSING */
  showPreview: boolean;
  setShowPreview: (v: boolean) => void;
  setShowResults: (v: boolean) => void;
  setTestEnd: (v: boolean) => void;
  setHidePreviewBar: (v: boolean) => void;
  solutionQuestionList: any[];
  selectedLanguage: string;
  returnToTestListAfterSubmit: boolean;
  onSubmitStart: () => void;
}

export default function InlineQuiz({
  testData,
  answers,
  setAnswers,
  currentQuestion,
  setCurrentQuestion,
  marked,
  setMarked,
  timeLeft,
  formatTime,
  next,
  prev,
  score,
  showResults,
  showSolution,
  setShowSolution,
  confirmSubmit,
  setConfirmSubmit,
  saveTest,
  getTestResultdata,
  exitFullscreen,
  totalDuration,
  setTimeTaken,
  scrollToTop,
  showPreview,
  setShowPreview,
  setShowResults,
  setTestEnd,
  setHidePreviewBar,
  solutionQuestionList,
  selectedLanguage,
  returnToTestListAfterSubmit,
  onSubmitStart,
}: Props) {
  const router = useRouter();
  const [showExplanation, setShowExplanation] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const submittingRef = useRef(false);
  const { language } = useLanguage();
  const text = getTranslation(language).inlineQuiz;
  const renderText = (
    template: string,
    values: Record<string, string | number>,
  ) =>
    Object.entries(values).reduce(
      (acc, [key, value]) => acc.replace(`{${key}}`, String(value)),
      template,
    );
  const sections = testData?.test_sections || [];
  const englishQuestions =
    Array.isArray(testData?.questions) && testData.questions.length > 0
      ? testData.questions
      : [];

  const hindiQuestions =
    Array.isArray(testData?.questions_hindi) &&
    testData.questions_hindi.length > 0
      ? testData.questions_hindi
      : [];

  // 🔁 language-aware with fallback both ways
  const questions =
    selectedLanguage === "hindi"
      ?  hindiQuestions
        : englishQuestions;
      

  const buildSectionMap = (sections: any[], questions: any[]) => {
    let startIndex = 0;

    return sections.map((section) => {
      const count = questions.filter(
        (q) => q.section_id === section.section_id,
      ).length;

      const mapped = {
        ...section,
        startIndex,
        count,
      };

      startIndex += count;
      return mapped;
    });
  };
  const sectionMap = React.useMemo(() => {
    if (!sections.length) return [];
    return buildSectionMap(sections, questions);
  }, [sections, questions]);

  const [activeSectionId, setActiveSectionId] = useState(
    sectionMap?.[0]?.section_id || null,
  );

  if (!testData || !questions)
    return <div className="text-sm text-gray-600">{text.loading}</div>;

  const qlist = showSolution ? solutionQuestionList : questions; // backend questions array
  const cq = qlist[currentQuestion];

  const options = [
    cq.option_1,
    cq.option_2,
    cq.option_3,
    cq.option_4,
    cq.option_5,
    cq.option_6,
    cq.option_7,
    cq.option_8,
    cq.option_9,
    cq.option_10,
  ].filter(Boolean);

  const correctAnswerIndex = Number(cq.answer) - 1;
  const correct = answers.filter(
    (a, i) => a === Number(qlist[i].answer) - 1,
  ).length;
  const wrong = answers.filter(
    (a, i) => a !== undefined && a !== Number(qlist[i].answer) - 1,
  ).length;
  const skipped = qlist.length - (correct + wrong);
  const totalAttempted = correct + wrong;
  // if (!lesson.quiz)
  //   return (
  //     <div className="text-sm text-gray-600">
  //       No quiz available for this lesson.
  //     </div>
  //   );

  // if (!started) {
  //   return (
  //     <div className="flex flex-col items-center justify-center h-full p-6 bg-white rounded-2xl shadow-md">
  //       <p className="text-gray-700 text-sm mb-4 text-center">
  //         Complete 85% of the lesson video or audio to unlock this quiz.
  //       </p>
  //       <Button onClick={start} className="bg-[#FAA631] hover:bg-[#e3952c] text-white px-6">
  //         Start Quiz
  //       </Button>
  //     </div>
  //   );
  // }
  const select = (idx: number) => {
    const copy = [...answers];
    copy[currentQuestion] = idx;
    setAnswers(copy);
  };

  useEffect(() => {
    if (!sectionMap?.length) return;

    const current = sectionMap?.find(
      (s) =>
        currentQuestion >= s.startIndex &&
        currentQuestion < s.startIndex + s.count,
    );

    if (current && current.section_id !== activeSectionId) {
      setActiveSectionId(current.section_id);
    }
  }, [currentQuestion, sectionMap]);

  const beginSubmission = () => {
    if (submittingRef.current) return false;

    submittingRef.current = true;
    setIsSubmitting(true);
    onSubmitStart();
    setTestEnd(true);
    setHidePreviewBar(false);
    exitFullscreen();
    return true;
  };

  const handleAutoSubmit = async () => {
    if (!beginSubmission()) return;

    try {
      setTimeTaken(totalDuration); // full time used

      await saveTest();

      // Mock, pre-certification, and final exams should return to the test
      // list after submission. Reloading also fetches the latest result state.
      if (returnToTestListAfterSubmit) {
        window.location.reload();
        return;
      }

      setShowResults(true);
      await getTestResultdata();
    } catch (err) {
      console.error("Auto submit failed", err);
      submittingRef.current = false;
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    if (timeLeft === 0 && !showResults) {
      handleAutoSubmit();
    }
  }, [timeLeft]);

  const markForReview = () => {
    const copy = [...marked];
    copy[currentQuestion] = !copy[currentQuestion];
    setMarked(copy);
  };

  if (isSubmitting) {
    return (
      <div className="min-h-[600px] w-full flex flex-col items-center justify-center gap-4 text-center">
        <div className="h-12 w-12 animate-spin rounded-full border-4 border-[#FAA631]/30 border-t-[#FAA631]" />
        <p className="text-xl font-semibold text-gray-800">Submitting quiz...</p>
        <p className="text-sm text-gray-500">
          Please wait while we save your answers.
        </p>
      </div>
    );
  }


  if (showResults) {
    const s = score();
    const correct = 10; // replace with dynamic values
    const wrong = 8;
    const skipped = 7;
    const totalAttempted = correct + wrong;

    return (
      <div className="min-h-screen w-full bg-[#FFF8F2] flex justify-center px-4 py-10">
        <div className="w-full max-w-3xl flex flex-col gap-6">
          <div className="w-full bg-gradient-to-br from-[#FAA631] to-[#F89E43] text-white rounded-3xl p-8 shadow-lg flex flex-col sm:flex-row items-center justify-between">
            <div className="flex flex-col text-left">
              <p className="text-lg sm:text-xl font-medium mb-2">
                {text.scoreIntro}
              </p>
              <p className="text-6xl sm:text-7xl font-bold leading-none">{s}</p>
              <p className="text-lg sm:text-xl mt-2">
                {renderText(text.outOf, { count: qlist.length })}
              </p>
            </div>

            <div className="flex justify-center items-center mt-6 sm:mt-0">
              <Image
                src="/images/winner.svg"
                alt={text.trophyAlt}
                width={200} // match the largest size used in UI
                height={200}
                className="w-[140px] sm:w-[200px] drop-shadow-xl"
              />
            </div>
          </div>

          <div className="bg-[#FFE8C8] text-gray-900 text-center p-4 rounded-xl shadow-md flex items-center justify-center gap-3">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="w-6 h-6 text-[#FAA631]"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
            <span className="text-sm sm:text-base font-medium">
              {renderText(text.timeTaken, { time: "23min 14sec" })}
            </span>
          </div>

          <div className="bg-white rounded-2xl shadow-md p-6">
            <div className="grid grid-cols-3 gap-6 text-center text-gray-700 font-medium mb-3">
              <div className="flex flex-col gap-1">
                <p>{text.correct}</p>
                <p className="text-2xl font-bold text-green-600">{correct}</p>
              </div>

              <div className="flex flex-col gap-1">
                <p>{text.wrong}</p>
                <p className="text-2xl font-bold text-red-500">{wrong}</p>
              </div>

              <div className="flex flex-col gap-1">
                <p>{text.skipped}</p>
                <p className="text-2xl font-bold text-gray-500">{skipped}</p>
              </div>
            </div>

            <p className="text-green-700 font-medium text-center mt-2">
              {renderText(text.totalAttempted, {
                count: totalAttempted,
              })}
            </p>
          </div>

          <div className="flex flex-col gap-4 mt-4">
            <button
              onClick={() => {
                scrollToTop();
                setShowPreview(false);
                setShowResults(false);
                setConfirmSubmit(false);
                setCurrentQuestion(0);
                setShowSolution(true);
              }}
              className="bg-[#FAA631] text-white font-semibold py-3 rounded-xl shadow hover:bg-[#f89e43] transition"
            >
              {text.viewSolution}
            </button>

            <button
              onClick={() => router.push("/")}
              className="border-2 border-[#FAA631] text-[#FAA631] font-semibold py-3 rounded-xl hover:bg-[#FFF3E3] transition"
            >
              {text.goHome}
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="relative w-full">
      {confirmSubmit && (
        <div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="w-[90%] sm:w-[480px] bg-white rounded-2xl p-6 shadow-2xl">
            {/* Title */}
            <h2 className="text-center text-lg font-semibold text-gray-900 mb-6">
              {text.submitTitle}
            </h2>

            {/* Stats */}
            <div className="space-y-4 mb-6">
              {/* Time Left */}
              <div className="flex justify-between items-center bg-orange-50 border border-orange-200 rounded-xl px-4 py-3">
                <div className="flex items-center gap-3">
                  <span className="text-orange-500 text-xl">⏱</span>
                  <p className="font-medium text-gray-700">{text.timeLeft}</p>
                </div>
                <p className="font-semibold text-gray-900">
                  {formatTime(timeLeft)}
                </p>
              </div>

              {/* Answered */}
              <div className="flex justify-between items-center bg-green-50 border border-green-200 rounded-xl px-4 py-3">
                <div className="flex items-center gap-3">
                  <span className="text-green-600 text-xl">✔</span>
                  <p className="font-medium text-gray-700">
                    {text.answeredQuestions}
                  </p>
                </div>
                <p className="font-semibold text-green-700">
                  {answers.filter((a) => a !== undefined).length}
                </p>
              </div>

              {/* Unanswered */}
              <div className="flex justify-between items-center bg-blue-50 border border-blue-200 rounded-xl px-4 py-3">
                <div className="flex items-center gap-3">
                  <span className="text-blue-600 text-xl">●</span>
                  <p className="font-medium text-gray-700">
                    {text.unansweredQuestions}
                  </p>
                </div>
                <p className="font-semibold text-blue-700">
                  {qlist.length - answers.filter((a) => a !== undefined).length}
                </p>
              </div>

              {/* Marked as Review */}
              <div className="flex justify-between items-center bg-orange-50 border border-orange-200 rounded-xl px-4 py-3">
                <div className="flex items-center gap-3">
                  <span className="text-orange-500 text-xl">🔖</span>
                  <p className="font-medium text-gray-700">
                    {text.markedForReview}
                  </p>
                </div>
                <p className="font-semibold text-orange-600">
                  {marked.filter((m) => m).length}
                </p>
              </div>
            </div>

            {/* Buttons */}
            <div className="flex gap-4">
              <button
                className="w-1/2 py-3 border-2 border-gray-300 rounded-xl font-semibold text-gray-700"
                onClick={() => setConfirmSubmit(false)}
              >
                {text.cancel}
              </button>

              <button
                className="w-1/2 py-3 bg-orange-500 text-white rounded-xl font-semibold shadow-md"
                onClick={async () => {
                  if (!beginSubmission()) return;

                  setTimeTaken(totalDuration - timeLeft);
                  try {
                    await saveTest();

                    // Do not show the in-test result UI for mock, pre, or final
                    // exams. The refreshed list displays the API's result status.
                    if (returnToTestListAfterSubmit) {
                      window.location.reload();
                      return;
                    }

                    setShowResults(true);
                    await getTestResultdata();
                  } catch (err) {
                    console.error("Submit quiz failed", err);
                    submittingRef.current = false;
                    setIsSubmitting(false);
                  }
                }}
              >
                {text.submitQuiz}
              </button>
            </div>
          </div>
        </div>
      )}

      {showSolution ? (
        <>
          <div className="flex justify-between items-center mb-4">
            {/* <div className="flex items-center gap-2 text-[#FAA631] font-medium">
              <Clock className="w-4 h-4" />
              <span>{formatTime(timeLeft)}</span>
            </div> */}

            <button
              onClick={() => {
                if (typeof window !== "undefined") {
                  window.location.reload();
                }
              }}
              className="text-sm text-gray-500 hover:text-gray-700"
            >
              <X size={30} />
            </button>
          </div>

          <div className="bg-[#FFF3E3] rounded-3xl p-6 text-center flex flex-col justify-center items-center min-h-[200px] shadow-sm relative mb-8">
            {/* <p className="text-gray-900 text-lg sm:text-xl font-medium mb-6 px-4">
                 
               </p> */}
            <p dangerouslySetInnerHTML={{ __html: cq.question }} />
            <div className="bg-[#FFF3E3] absolute bottom-[-18px] border border-[#F89E43] rounded-full px-5 py-1 text-[#F89E43] font-medium">
              {renderText(text.question, {
                current: currentQuestion + 1,
                total: qlist.length,
              })}
            </div>
          </div>

          <div className="space-y-3 mb-6">
            {options.map((opt, i) => {
              const isCorrect = i === correctAnswerIndex;
              const isWrong = answers[currentQuestion] === i && !isCorrect;
              return (
                <div
                  key={i}
                  dangerouslySetInnerHTML={{ __html: `${i + 1}. ${opt}` }}
                  className={`p-3 rounded-xl border ${
                    isCorrect
                      ? "bg-green-100 border-green-600"
                      : isWrong
                        ? "bg-red-100 border-red-600"
                        : "bg-white border-gray-300"
                  }`}
                />
              );
            })}
          </div>
          <div className="flex justify-between items-center mb-4">
            <p className="text-gray-900 font-medium">
              {renderText(text.yourAnswer, {
                answer:
                  answers[currentQuestion] !== undefined
                    ? answers[currentQuestion] + 1
                    : text.notAnswered,
              })}
            </p>

            {/* Correct Answer Index from API (1-based → convert to 0-based) */}
            {answers[currentQuestion] === Number(cq.answer) - 1 ? (
              // Correct Answer UI
              <div className="flex items-center gap-2">
                <span className="text-green-600 font-semibold">
                  +{cq.marks_per_question || 1}
                </span>
                <span className="bg-green-500 text-white rounded-full px-3 py-1 text-sm">
                  {text.correctStatus}
                </span>
              </div>
            ) : (
              // Wrong Answer UI
              <div className="flex items-center gap-2">
                <span className="text-red-600 font-semibold">
                  -{cq.negative_marks || 0}
                </span>
                <span className="bg-red-500 text-white rounded-full px-3 py-1 text-sm">
                  {text.incorrectStatus}
                </span>
              </div>
            )}
          </div>

          {/* Explanation Accordion */}
          <div
            className="bg-[#D9F5E4] p-4 rounded-xl cursor-pointer"
            onClick={() => setShowExplanation(!showExplanation)}
          >
            <div className="flex justify-between items-center">
              <span className="font-medium">{text.explanation}</span>
              <span className="text-xl">{showExplanation ? "▲" : "▼"}</span>
            </div>

            {showExplanation && (
              // <p className="text-gray-700 mt-3 text-sm sm:text-base text-left">
              //   {cq.description || "No explanation provided."}
              // </p>
              <p
                dangerouslySetInnerHTML={{
                  __html: cq.description || text.noExplanation,
                }}
              />
            )}
          </div>

          <div className="flex justify-between items-center mt-6">
            <Button
              variant="outline"
              onClick={prev}
              disabled={currentQuestion === 0}
              className="flex items-center gap-2"
            >
              <ChevronLeft className="w-4 h-4" /> {text.prev}
            </Button>
            {currentQuestion < qlist.length - 1 && (
              <Button
                onClick={next}
                disabled={currentQuestion === qlist.length - 1}
                className="bg-[#FAA631] text-white px-6 flex items-center gap-2"
              >
                {text.next} <ChevronRight className="w-4 h-4" />
              </Button>
            )}
          </div>
        </>
      ) : (
        <>
          <div
            className={`${
              showPreview ? "opacity-60" : "opacity-100"
            } transition`}
          >
            <div className="w-full p-4 sm:p-6 rounded-2xl flex flex-col">
              {sectionMap.length >= 2 && (
                <div className="mb-4">
                  <label className="text-sm font-medium text-gray-700 mb-1 block">
                    {text.section}
                  </label>

                  <select
                    value={activeSectionId}
                    onChange={(e) => {
                      const selected = sectionMap.find(
                        (s) => s.section_id === e.target.value,
                      );
                      if (!selected) return;

                      setActiveSectionId(selected.section_id);
                      setCurrentQuestion(selected.startIndex);
                      scrollToTop();
                    }}
                    className="w-[50%] border rounded-xl px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[#FAA631]"
                  >
                    {sectionMap.map((sec) => (
                      <option key={sec.section_id} value={sec.section_id}>
                        {renderText(text.sectionOption, {
                          name: sec.name,
                          count: sec.count,
                        })}
                      </option>
                    ))}
                  </select>
                </div>
              )}

              {/* Sticky Timer Bar */}
              <div className="sticky top-0 z-10 bg-white py-3 border-b border-gray-100">
                <div className="flex justify-between items-center">
                  <div className="flex items-center gap-2 text-[#FAA631] font-medium">
                    <Clock className="w-4 h-4" />
                    <span>{formatTime(timeLeft)}</span>
                  </div>
                  <button
                    onClick={markForReview}
                    className={`flex items-center gap-2 text-sm ${
                      marked[currentQuestion]
                        ? "text-[#FAA631]"
                        : "text-gray-700"
                    }`}
                  >
                    {text.markAsReview} <Bookmark className="w-4 h-4" />
                  </button>
                </div>
              </div>

              {/* Scrollable content */}
              <div className="max-h-[60vh] overflow-y-auto py-4">
                <div className="bg-[#FFF3E3] rounded-3xl p-6 text-center flex flex-col justify-center items-center min-h-[200px] shadow-sm relative mb-8">
                  <p dangerouslySetInnerHTML={{ __html: cq.question }} />
                  <div className="bg-[#FFF3E3] absolute bottom-[-18px] border border-[#F89E43] rounded-full px-5 py-1 text-[#F89E43] font-medium">
                    {renderText(text.question, {
                      current: currentQuestion + 1,
                      total: qlist.length,
                    })}
                  </div>
                </div>

                <div className="space-y-3 mb-6">
                  {options.map((opt, i) => (
                    <div
                      key={i}
                      onClick={() => select(i)}
                      dangerouslySetInnerHTML={{ __html: `${i + 1}. ${opt}` }}
                      className={`p-3 rounded-xl border cursor-pointer ${
                        answers[currentQuestion] === i
                          ? "border-[#FAA631] bg-[#FFF3E3]"
                          : "border-gray-300 hover:bg-gray-100"
                      }`}
                    />
                  ))}
                </div>
              </div>

              {/* Sticky Navigation Buttons */}
              <div className="sticky bottom-0 z-10 bg-white py-3 border-t border-gray-100">
                <div className="flex justify-between items-center">
                  <Button
                    variant="outline"
                    onClick={prev}
                    disabled={currentQuestion === 0}
                    className="flex items-center gap-2"
                  >
                    <ChevronLeft className="w-4 h-4" /> {text.prev}
                  </Button>
                  <Button
                    onClick={next}
                    className="bg-[#FAA631] text-white px-6 flex items-center gap-2"
                  >
                    {currentQuestion === qlist.length - 1
                      ? text.finish
                      : text.next}
                    <ChevronRight className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
