"use client";

import Image from "next/image";
import { X } from "lucide-react";
import { ModalWrapper } from "./ModalWrapper";
import { getTranslation } from "@/src/hooks/useTranslation";
import { useLanguage } from "@/src/hooks/LanguageContext";
import { decodeHtml } from "@/lib/commonFunctions";

type InstructionsModalProps = {
  show: boolean;
  instructionData: any;
  onContinue: () => void;
  onClose?: () => void;
};

export function InstructionsModal({
  show,
  instructionData,
  onContinue,
  onClose,
}: InstructionsModalProps) {
  if (!show) return null;
  const { language } = useLanguage();
  const text = getTranslation(language).instructionsModal;
  const renderText = (
    template: string,
    values: Record<string, string | number>,
  ) =>
    Object.entries(values).reduce(
      (acc, [key, value]) => acc.replace(`{${key}}`, String(value)),
      template,
    );

  const basic = instructionData?.test_basic;
  const sections = instructionData?.test_sections || [];
  

  const testName = language === "hindi" ? basic?.test_series_name_hindi : basic?.test_series_name || text.defaultTestName;
  const totalQuestions = Number(basic?.total_questions || 0);
  const totalMarks = Number(basic?.total_marks || 0);
  const totalTime = Number(basic?.time_in_mins || 0);
  const description = language === "hindi" ? decodeHtml(basic?.description_hindi) : decodeHtml(basic?.description) || "";
  const isReattempt = String(basic?.is_reattempt) === "1";

  return (
    <ModalWrapper>
      <div className="bg-white rounded-3xl w-[92%] max-w-2xl max-h-[90vh] overflow-hidden shadow-2xl border border-gray-100">
        {/* Header */}
        <div className="px-6 py-5 border-b flex items-start justify-between gap-4">
          <div className="flex items-start gap-3">
            <div className="w-11 h-11 rounded-2xl bg-[#FFF4E4] flex items-center justify-center shrink-0">
              <Image
                src="/images/bulb-lighting.svg"
                alt={text.iconAlt}
                width={22}
                height={22}
              />
            </div>

            <div>
              <p className="text-sm font-semibold text-[#FF8A00]">
                {text.header}
              </p>
              <h2 className="text-lg sm:text-xl font-bold text-gray-900 leading-tight">
                {decodeHtml(testName)}
              </h2>
              <p className="text-xs sm:text-sm text-gray-500 mt-1">
                {text.subtitle}
              </p>
            </div>
          </div>

          {onClose && (
            <button
              type="button"
              onClick={onClose}
              className="w-10 h-10 rounded-full bg-gray-100 hover:bg-gray-200 transition flex items-center justify-center active:scale-95"
              aria-label={text.closeAria}
            >
              <X size={18} className="text-gray-700" />
            </button>
          )}
        </div>

        {/* Body */}
        <div className="px-6 py-5 overflow-y-auto max-h-[calc(90vh-160px)]">
          {/* Overview Cards */}
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            <div className="rounded-2xl border bg-[#FFF9F1] p-4">
              <p className="text-xs text-gray-500">{text.questions}</p>
              <p className="text-lg font-bold text-gray-900">
                {totalQuestions}
              </p>
            </div>

            <div className="rounded-2xl border bg-[#FFF9F1] p-4">
              <p className="text-xs text-gray-500">{text.marks}</p>
              <p className="text-lg font-bold text-gray-900">
                {totalMarks}
              </p>
            </div>

            <div className="rounded-2xl border bg-[#FFF9F1] p-4">
              <p className="text-xs text-gray-500">{text.time}</p>
              <p className="text-lg font-bold text-gray-900">
                {totalTime} {text.minuteShort}
              </p>
            </div>

            {/* <div className="rounded-2xl border bg-[#FFF9F1] p-4">
              <p className="text-xs text-gray-500">Reattempt</p>
              <p
                className={`text-sm font-bold ${
                  isReattempt ? "text-green-600" : "text-gray-900"
                }`}
              >
                {isReattempt ? "Allowed" : "Not Allowed"}
              </p>
            </div> */}
          </div>

          {/* Description */}
          {description?.trim() && (
            <div className="mt-5 rounded-2xl border bg-white p-4">
              <p className="text-sm font-semibold text-gray-900 mb-2">
                {text.aboutTest}
              </p>
              <p className="text-sm text-gray-600 leading-relaxed">
                {description}
              </p>
            </div>
          )}

          {/* Sections */}
          <div className="mt-6">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-base sm:text-lg font-bold text-gray-900">
                {text.sections} ({sections.length})
              </h3>
              <span className="text-xs text-gray-500">
                {text.sectionDetails}
              </span>
            </div>

            {sections.length > 0 ? (
              <div className="space-y-3">
                {sections.map((sec: any, idx: number) => {
                  const secName =
                    sec?.name ||
                    renderText(text.sectionFallback, {
                      index: idx + 1,
                    });
                  const secTime = Number(sec?.section_timing || 0);
                  const secQuestions = Number(sec?.total_questions || 0);
                  const marksPerQ = Number(sec?.marks_per_question || 0);
                  const negative = Number(sec?.negative_marks || 0);

                  return (
                    <div
                      key={sec?.id || idx}
                      className="rounded-2xl border bg-white p-4 hover:shadow-sm transition"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <div className="flex-1">
                          <p className="text-sm font-bold text-gray-900">
                            {idx + 1}. {secName}
                          </p>
                          <p className="text-xs text-gray-500 mt-1">
                            {renderText(text.questionsWithTime, {
                              questions: secQuestions,
                              time: secTime,
                            })}
                          </p>
                        </div>

                        <div className="text-right">
                          <p className="text-xs text-gray-500">
                            {text.marksPerQuestion}
                          </p>
                          <p className="text-sm font-bold text-gray-900">
                            {marksPerQ}
                          </p>
                        </div>
                      </div>

                      <div className="mt-3 flex flex-wrap gap-2">
                        <span className="text-xs px-3 py-1 rounded-full bg-[#FFF4E4] text-[#FF8A00] font-semibold">
                          {renderText(text.negative, {
                            value: negative,
                          })}
                        </span>

                        <span className="text-xs px-3 py-1 rounded-full bg-gray-100 text-gray-700 font-medium">
                          {renderText(text.timing, {
                            value: secTime,
                          })}
                        </span>

                        <span className="text-xs px-3 py-1 rounded-full bg-gray-100 text-gray-700 font-medium">
                          {renderText(text.questionCount, {
                            value: secQuestions,
                          })}
                        </span>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="rounded-2xl border bg-white p-4 text-sm text-gray-600">
                {text.noSections}
              </div>
            )}
          </div>

          {/* General Instructions (Optional Static UX improvement) */}
          <div className="mt-6 rounded-2xl border bg-[#FFF9F1] p-4 mb-20">
            <p className="text-sm font-semibold text-gray-900 mb-2">
              {text.importantNotes}
            </p>
            <ul className="text-sm text-gray-700 space-y-2">
              <li>• {text.note1}</li>
              <li>• {text.note2}</li>
              <li>• {text.note3}</li>
            </ul>
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-4 border-t bg-white sticky bottom-0">
          <button
            onClick={onContinue}
            className="w-full bg-[#FAA631] hover:bg-[#e18b20] text-white py-3 rounded-full font-semibold transition active:scale-[0.99]"
          >
            {text.continue}
          </button>

          {onClose && (
            <button
              onClick={onClose}
              className="w-full mt-3 py-3 rounded-full font-medium text-gray-700 hover:bg-gray-100 transition"
            >
              {text.cancel}
            </button>
          )}
        </div>
      </div>
    </ModalWrapper>
  );
}
