"use client";

import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { useState } from "react";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";

interface ViewSolutionProps {
  questions: any[];
  currentQuestion: number;
  setCurrentQuestion: React.Dispatch<React.SetStateAction<number>>;
  onClose: () => void;
}

export default function ViewSolution({
  questions,
  onClose,
  currentQuestion,
  setCurrentQuestion,
}: ViewSolutionProps) {
  //   const [currentQuestion, setCurrentQuestion] = useState(0);
  const [showExplanation, setShowExplanation] = useState(false);
  const { language } = useLanguage();
  const text = getTranslation(language).viewSolution;
  const renderText = (
    template: string,
    values: Record<string, string | number>,
  ) =>
    Object.entries(values).reduce(
      (acc, [key, value]) => acc.replace(`{${key}}`, String(value)),
      template,
    );

  const cq = questions[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 correctIndex = Number(cq.answer) - 1;
  const userIndex = getUserAnswerIndex(cq.answers);

  return (
    <div className="w-full">
      {/* HEADER */}
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-lg font-semibold">{text.title}</h2>
        <button
          onClick={onClose}
          className="text-sm text-gray-500 hover:text-gray-700"
        >
          <X size={30} />
        </button>
      </div>

      {/* QUESTION */}
      <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: questions.length,
          })}
        </div>
      </div>

      {/* OPTIONS */}
      <div className="space-y-3 mb-6">
        {options.map((opt, i) => {
          const isCorrect = i === correctIndex;
          const isWrong = i === userIndex && i !== correctIndex;

          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>

      {/* ANSWER STATUS */}
      <div className="flex justify-between items-center mb-4">
        <p className="font-medium text-gray-800">
          {renderText(text.yourAnswer, {
            answer: userIndex !== -1 ? userIndex + 1 : text.notAnswered,
          })}
        </p>

        {userIndex === correctIndex ? (
          <span className="bg-green-500 text-white rounded-full px-3 py-1 text-sm">
            {text.correct}
          </span>
        ) : (
          <span className="bg-red-500 text-white rounded-full px-3 py-1 text-sm">
            {text.incorrect}
          </span>
        )}
      </div>

      {/* EXPLANATION */}
      <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>{showExplanation ? "▲" : "▼"}</span>
        </div>

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

      {/* NAVIGATION */}
      <div className="flex justify-between items-center mt-6">
        <button
          disabled={currentQuestion === 0}
          onClick={() => setCurrentQuestion((q) => q - 1)}
          className="flex items-center gap-2 px-4 py-2 border rounded-xl disabled:opacity-50"
        >
          <ChevronLeft size={18} /> {text.prev}
        </button>
        {currentQuestion < questions.length - 1 && (
          <button
            onClick={() => setCurrentQuestion((q) => q + 1)}
            className="flex items-center gap-2 px-4 py-2 bg-[#FAA631] text-white rounded-xl"
          >
            {text.next} <ChevronRight size={18} />
          </button>
        )}
      </div>
    </div>
  );
}

/* 🔹 Helper */
function getUserAnswerIndex(answers: string[]) {
  return answers?.findIndex((a) => a === "1");
}
