"use client";

import { ChevronLeft } from "lucide-react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";

interface Props {
  testResult: any; // API response (testResult.data)
  formatTime: (seconds: number) => string;
  scrollToTop: () => void;
  setShowPreview: (v: boolean) => void;
  setShowResults: (v: boolean) => void;
  setConfirmSubmit: (v: boolean) => void;
  setCurrentQuestion: (v: number) => void;
  setShowSolution: (v: boolean) => void;
  gocod: String;
}

export default function TestResultUI({
  testResult,
  formatTime,
  scrollToTop,
  setShowPreview,
  setShowResults,
  setConfirmSubmit,
  setCurrentQuestion,
  setShowSolution,
  gocod,
}: Props) {
  const router = useRouter();
  const { language } = useLanguage();
  const text = getTranslation(language).testResult;
  const renderText = (
    template: string,
    values: Record<string, string | number>,
  ) =>
    Object.entries(values).reduce(
      (acc, [key, value]) => acc.replace(`{${key}}`, String(value)),
      template,
    );
  /* =========================
     DIRECT NORMALIZATION
  ========================= */
  const marks = Number(testResult?.marks ?? 0);
  const totalMarks = Number(testResult?.total_marks ?? 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;

  /* =========================
     UI
  ========================= */
  return (
    <div className="min-h-screen w-full bg-[#FFF4E4] px-4 py-10 sm:py-16 mt-12">
      <div className="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-10">
        {/* LEFT SECTION */}
        <div className="relative flex flex-col gap-10">
          {/* SCORE CARD */}
          <button
              onClick={() => {
                setTimeout(() => {
                  window.location.reload();
                }, 100);
              }}
              className="absolute top-[-50px] left-0 flex items-center gap-2 px-4 py-2 bg-white border rounded-lg shadow-sm hover:bg-gray-50 transition"
            >
              <ChevronLeft className="w-4 h-4" color="black" />
              <span className="text-black">{text.back}</span>
            </button>
          {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">{text.scoreIntro}</p>

            <p className="text-[60px] sm:text-[120px] font-extrabold drop-shadow-xl leading-none">
              {marks}
            </p>

            <p className="text-lg sm:text-xl">
              {renderText(text.outOf, { count: totalMarks })}
            </p>

            <Image
              src="/images/winner.svg"
              alt={text.trophyAlt}
              width={260}
              height={260}
              className="w-[200px] sm:w-[260px] drop-shadow-xl"
            />
          </div>

          {/* TIME TAKEN */}
          <div className="bg-white border border-[#FFD8A4] rounded-2xl shadow p-6 flex items-center justify-center gap-4 font-medium text-gray-900">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="w-8 h-8 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-lg">
              {renderText(text.timeTaken, {
                time: formatTime(timeTaken),
              }).split(formatTime(timeTaken))[0]}
              <b>{formatTime(timeTaken)}</b>
              {renderText(text.timeTaken, {
                time: formatTime(timeTaken),
              }).split(formatTime(timeTaken))[1]}
            </span>
          </div>

          {/* PERFORMANCE GRID */}
          <div className="bg-white rounded-3xl shadow-xl p-8">
            <h3 className="text-2xl font-bold text-[#FAA631] text-center mb-6">
              {text.performance}
            </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">{text.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">{text.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">{text.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">
              {renderText(text.totalAttempted, {
                count: totalAttempted,
              })}
            </p>
          </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]">
                {text.detailedAnalysis}
              </h3>

              <ul className="text-gray-700 space-y-3 text-lg">
                <li>
                  ✔{" "}
                  {renderText(text.accuracy, {
                    value: testResult?.accuracy,
                  })}
                </li>
                <li>
                  ✔{" "}
                  {renderText(text.correctAnswers, {
                    value: correct,
                  })}
                </li>
                <li>
                  ❌{" "}
                  {renderText(text.incorrectAnswers, {
                    value: wrong,
                  })}
                </li>
                <li>
                  ⏳{" "}
                  {renderText(text.analysisTimeTaken, {
                    value: formatTime(timeTaken),
                  })}
                </li>
              </ul>
            </div>
          )}
        </div>

        {/* RIGHT SECTION */}
        <div className="flex flex-col gap-10">
          {/* RANK CARD */}
          {/* <div className="bg-white rounded-3xl shadow-xl p-8 flex flex-col gap-4">
            <h3 className="text-2xl font-bold text-[#FAA631]">{text.rank}</h3>
            <p className="text-gray-600 text-lg">{text.basedOnParticipants}</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">
                {renderText(text.outOfStudents, {
                  count: totalParticipants || "--",
                })}
              </p>
            </div>
          </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]">
                {text.detailedAnalysis}
              </h3>

              <ul className="text-gray-700 space-y-3 text-lg">
                <li>
                  ✔{" "}
                  {renderText(text.accuracy, {
                    value: testResult?.accuracy,
                  })}
                </li>
                <li>
                  ✔{" "}
                  {renderText(text.correctAnswers, {
                    value: correct,
                  })}
                </li>
                <li>
                  ❌{" "}
                  {renderText(text.incorrectAnswers, {
                    value: wrong,
                  })}
                </li>
                <li>
                  ⏳{" "}
                  {renderText(text.analysisTimeTaken, {
                    value: 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]">
                {text.certificate}
              </h3>
              <div className="mt-0">
                <Image
                  src={testResult?.certificate_url}
                  alt={text.certificateAlt}
                  width={800}
                  height={600}
                  className="w-full h-auto rounded-xl border border-gray-300 shadow"
                />
              </div>
            </div>
          )}

          {/* NEXT STEPS */}
          <div className="bg-white rounded-3xl shadow-xl p-8 flex flex-col gap-6">
            <h3 className="text-2xl font-bold text-[#FAA631]">
              {text.whatsNext}
            </h3>

            <p className="text-gray-700 text-lg">{text.nextDescription}</p>

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

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