"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { getTestResult } from "@/lib/api/testSeriesApi";
import Image from "next/image";
import ViewSolution from "@/app/quiz/components/ViewSolution";
import QuizSidebar from "@/app/quiz/components/QuizSidebar";
import { getStoredLanguage } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";
import { getActiveCourseId } from "@/lib/courseSelection";

export default function ResultPage() {
  const { testId } = useParams<{ testId: string }>();
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [testResult, setTestResult] = useState<any>(null);
  const [showSolution, setShowSolution] = useState(false);
  const [solutionIndex, setSolutionIndex] = useState(0);
  const { language } = useLanguage();
  const lang = getStoredLanguage();
  const [gocod, setGocod] = useState("");
  const t = getTranslation(lang).resultPage;

  useEffect(() => {
    if (!testId) return;

    const token = localStorage.getItem("token");
    const userData = localStorage.getItem("user_data");
    const courseId = getActiveCourseId();
    const registerDetails = localStorage.getItem("register_details");
    let register = null;
    if (!token || !userData || !courseId) {
      router.replace("/login");
      return;
    }

    const user = JSON.parse(userData);
    register = registerDetails ? JSON.parse(registerDetails) : null;

    if (user?.gocod) {
      setGocod(user?.gocod);
    } else if (register?.gocod) {
      setGocod(register?.gocod);
    }

    const fetchResult = async () => {
      try {
        const res = await getTestResult(user.id, testId, courseId, "1");
        if (res?.data) setTestResult(res.data);
      } catch (err) {
        console.error("Result fetch failed", err);
      } finally {
        setLoading(false);
      }
    };

    fetchResult();
  }, [testId, router]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        {t.loading}
      </div>
    );
  }

  if (!testResult) {
    return (
      <div className="min-h-screen flex items-center justify-center text-red-500">
        {t.notAvailable}
      </div>
    );
  }

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

  const correct = Number(testResult?.correct_count ?? 0);
  const wrong = Number(testResult?.incorrect_count ?? 0);
  const skipped = Number(testResult?.non_attempt ?? 0);
  const totalAttempted = correct + wrong;
  const rank = testResult?.user_rank ? Number(testResult.user_rank) : null;
  const totalParticipants = Number(testResult?.total_user_attempt ?? 0);
  const totalTimeInSec = Number(testResult?.time_in_mins ?? 0) * 60;
  const timeRemaining = Number(testResult?.time_remain ?? 0);
  const timeTaken = totalTimeInSec - timeRemaining;

  const solutionAnswers: number[] = testResult.questions.map((q: any) =>
    q.answers?.findIndex((a: string) => a === "1"),
  );
  const solutionMarked: boolean[] = testResult.questions.map(
    (q: any) => q.state === "marked_for_review",
  );

  const renderTemplate = (
    text: string,
    vars: Record<string, string | number>,
  ) =>
    Object.entries(vars).reduce(
      (acc, [key, value]) => acc.replace(`{${key}}`, String(value)),
      text,
    );

  return (
    <div className="min-h-screen w-full bg-[#FFF4E4] px-4 py-10 sm:py-16 mt-10">
      {testResult?.marks ? (
        <div className="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-10">
          <div className="flex flex-col gap-10">
            {gocod && (
              <div className="w-full bg-gradient-to-br from-[#FAA631] to-[#F89E43] text-white rounded-3xl p-10 shadow-2xl flex flex-col items-center gap-5">
                <p className="text-lg sm:text-xl font-medium">{gocod}</p>
              </div>
            )}
            <div className="w-full bg-gradient-to-br from-[#FAA631] to-[#F89E43] text-white rounded-3xl p-10 shadow-2xl flex flex-col items-center gap-5">
              <p className="text-lg sm:text-xl font-medium">{t.scoreIntro}</p>
              <p className="text-[60px] sm:text-[120px] font-extrabold drop-shadow-xl leading-none">
                {testResult?.marks}
              </p>
              <p className="text-lg sm:text-xl">
                {t.outOf} {testResult?.total_marks}
              </p>
              <Image
                src="/images/winner.svg"
                alt="Winner Trophy"
                width={260}
                height={260}
                className="w-[200px] sm:w-[260px] drop-shadow-xl"
              />
            </div>

            <div className="bg-white border border-[#FFD8A4] rounded-2xl shadow p-6 flex items-center justify-center gap-4 font-medium text-gray-900">
              <span className="text-lg">
                {renderTemplate(t.timeTakenSentence, {
                  time: formatTime(timeTaken),
                })}
              </span>
            </div>

            <div className="bg-white rounded-3xl shadow-xl p-8">
              <h3 className="text-2xl font-bold text-[#FAA631] text-center mb-6">
                {t.performanceTitle}
              </h3>
              <div className="grid grid-cols-3 gap-6 text-center">
                <div className="bg-[#E9FBEA] rounded-2xl p-6 shadow-sm">
                  <p className="text-gray-600">{t.correct}</p>
                  <p className="text-4xl font-bold text-green-600 mt-2">
                    {correct}
                  </p>
                </div>
                <div className="bg-[#FEECEC] rounded-2xl p-6 shadow-sm">
                  <p className="text-gray-600">{t.wrong}</p>
                  <p className="text-4xl font-bold text-red-500 mt-2">
                    {wrong}
                  </p>
                </div>
                <div className="bg-gray-100 rounded-2xl p-6 shadow-sm">
                  <p className="text-gray-600">{t.skipped}</p>
                  <p className="text-4xl font-bold text-gray-700 mt-2">
                    {skipped}
                  </p>
                </div>
              </div>
              <p className="text-[#16A34A] text-center font-semibold mt-6 text-lg">
                {t.attempted}: {totalAttempted}
              </p>
            </div>
          </div>

          <div className="flex flex-col gap-10">
            {/* <div className="bg-white rounded-3xl shadow-xl p-8 flex flex-col gap-4">
              <h3 className="text-2xl font-bold text-[#FAA631]">
                {t.rankTitle}
              </h3>
              <p className="text-gray-600 text-lg">{t.rankSubtitle}</p>
              <div className="text-center py-6 bg-[#FFF7EB] rounded-2xl border border-[#FFD8A4] shadow">
                <p className="text-5xl font-extrabold text-[#FAA631]">
                  {rank ?? "--"}
                </p>
                <p className="mt-2 text-gray-600">
                  {renderTemplate(t.outOfStudents, {
                    count: totalParticipants || "--",
                  })}
                </p>
              </div>
            </div> */}

            <div className="bg-white rounded-3xl shadow-xl p-8 flex flex-col gap-6">
              <h3 className="text-2xl font-bold text-[#FAA631]">
                {t.analysisTitle}
              </h3>
              <ul className="text-gray-700 space-y-3 text-lg">
                <li>
                  {t.accuracy}: {testResult?.accuracy}%
                </li>
                <li>
                  {t.correctAnswers}: {correct}
                </li>
                <li>
                  {t.incorrectAnswers}: {wrong}
                </li>
                <li>
                  {t.timeTaken}: {formatTime(timeTaken)}
                </li>
              </ul>
            </div>

            {testResult?.certificate_url && (
              <div className="bg-white rounded-3xl shadow-xl p-8 flex flex-col gap-6">
                <h3 className="text-2xl font-bold text-[#FAA631]">
                  {t.certificate}
                </h3>
                <Image
                  src={testResult.certificate_url}
                  alt="Certificate"
                  width={800}
                  height={600}
                  className="w-full h-auto rounded-xl border border-gray-300 shadow"
                />
              </div>
            )}

            <div className="bg-white rounded-3xl shadow-xl p-8 flex flex-col gap-6">
              <div className="flex flex-col gap-4 mt-4">
                <button
                  onClick={() => setShowSolution(true)}
                  className="bg-[#FAA631] text-white font-semibold py-3 rounded-xl shadow hover:bg-[#f89e43] transition"
                >
                  {t.viewSolution}
                </button>
                <button
                  onClick={() => router.push("/")}
                  className="border-2 border-[#FAA631] text-[#FAA631] font-semibold py-3 rounded-xl hover:bg-[#FFF3E3] transition"
                >
                  {t.goHome}
                </button>
              </div>
            </div>

            <div className="bg-white rounded-3xl shadow-xl p-8 flex flex-col gap-6">
              <h3 className="text-2xl font-bold text-[#FAA631]">
                {t.nextTitle}
              </h3>
              <p className="text-gray-700 text-lg">{t.nextDescription}</p>
            </div>
          </div>

          {showSolution && (
            <div className="fixed inset-0 bg-black/40 z-50 flex justify-center items-center p-4">
              <div className="bg-white max-w-7xl w-full rounded-3xl shadow-2xl overflow-hidden">
                <div className="flex h-[95vh]">
                  <div className="flex-1 p-6 overflow-y-auto">
                    <ViewSolution
                      questions={testResult.questions}
                      currentQuestion={solutionIndex}
                      setCurrentQuestion={setSolutionIndex}
                      onClose={() => setShowSolution(false)}
                    />
                  </div>
                  <div className="hidden lg:block w-[360px] border-l">
                    <QuizSidebar
                      title={
                        language === "hindi"
                          ? testResult?.test_series_name_hindi
                          : testResult?.test_series_name
                      }
                      qlist={testResult.questions}
                      answers={solutionAnswers}
                      marked={solutionMarked}
                      currentQuestion={solutionIndex}
                      setCurrentQuestion={setSolutionIndex}
                      setConfirmSubmit={() => {}}
                      showSolution={true}
                    />
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      ) : (
        <div className="max-w-3xl mx-auto bg-white rounded-3xl shadow-xl p-10 text-center flex flex-col items-center gap-6">
          <Image
            src="/images/pending.png"
            alt="Result Pending"
            width={220}
            height={220}
            className="opacity-90"
          />
          <h2 className="text-3xl font-bold text-gray-800">{t.pendingTitle}</h2>
          <p className="text-gray-600 text-lg max-w-xl">
            {t.pendingDescription}
          </p>
          {testResult?.result_date && (
            <p className="text-sm text-gray-500">
              {t.expectedDate}:{" "}
              <span className="font-medium">
                {new Date(Number(testResult.result_date)).toLocaleDateString()}
              </span>
            </p>
          )}
          <div className="flex flex-col sm:flex-row gap-4 mt-4">
            <button
              onClick={() => router.push("/")}
              className="px-8 py-3 rounded-xl bg-[#FAA631] text-white font-semibold shadow hover:bg-[#f89e43] transition"
            >
              {t.goHome}
            </button>
            <button
              onClick={() => router.back()}
              className="px-8 py-3 rounded-xl border-2 border-[#FAA631] text-[#FAA631] font-semibold hover:bg-[#FFF4E4] transition"
            >
              {t.back}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
