"use client";
import { useState, useEffect } from "react";

export default function MutiAnswerQS({
                                          text,
                                          options,
                                          tag,
                                          questionID,
                                          examAttemptID,
                                          resetSignal,
                                          locked, // قفل شدن سوال بعد از ثبت
                                      }) {
    const [selectedIndex, setSelectedIndex] = useState(null);
    const LOCAL_KEY = "exam_answer";

    // بارگذاری پاسخ ذخیره‌شده (در صورت وجود)
    useEffect(() => {
        const saved = JSON.parse(localStorage.getItem(LOCAL_KEY));
        if (saved && saved.question_id === questionID) {
            const idx = options.findIndex(
                (opt) => opt.id === saved.question_option_id
            );
            if (idx !== -1) setSelectedIndex(idx);
        } else {
            setSelectedIndex(null);
        }
    }, [questionID, options]);

    // ریست هنگام تغییر سوال
    useEffect(() => {
        setSelectedIndex(null);
    }, [resetSignal]);


    const handleSelect = (index) => {
        if (locked) return;

        const isUpdatePermitted = Number(localStorage.getItem("is_update_answer_permitted"));
        const answeredBefore = JSON.parse(localStorage.getItem("answered_questions")) || [];

        // 🚫 اگر تغییر پاسخ غیرفعاله (0) و این سؤال قبلاً جواب داده شده:
        if (isUpdatePermitted === 0 && answeredBefore.includes(questionID)) return;

        const selectedOption = options[index];
        const answer = {
            question_id: questionID,
            question_option_id: selectedOption.id,
            exam_attempt_id: examAttemptID,
        };

        localStorage.setItem("exam_answer", JSON.stringify(answer));
        setSelectedIndex(index);
    };
    return (
        <div className="grid gap-9">
            <div className="grid gap-3">
                <p className="text-secondary-main font-black text-t2 md:text-lg md:text-justify">
                    {text}
                </p>
                <p className="text-secondary-main text-xl md:text-sm">
                    (این سوال برای سنجش توانایی شما در {tag} می‌باشد)
                </p>
            </div>

            <div className="grid grid-cols-2 text-secondary-main gap-x-8 gap-y-4 md:grid-cols-1">
                {options.map((item, index) => (
                    <button
                        key={index}
                        onClick={() => handleSelect(index)}
                        disabled={locked}
                        className={`py-1.5 px-3 border-[1.5px] rounded-xl flex items-center justify-start gap-2 transition-all duration-200
                             ${
                            selectedIndex === index
                                ? "bg-success-lighten border-success-main text-success-dark"
                                : "bg-white border-secondary-main"
                        }
                              ${locked ? "opacity-60 cursor-not-allowed" : ""}
                                  `}
                    >
                        <div
                            className={`flex items-center justify-center border-[1.5px] rounded-lg w-9 h-9 md:w-7 md:h-7 text-lg font-bold
                            ${
                                selectedIndex === index
                                    ? "bg-success-main border-success-main text-white"
                                    : "bg-secondary-lighten border-secondary-main text-secondary-main"
                            }`}
                        >
                            {index + 1}
                        </div>
                        <p>{item.text}</p>
                    </button>
                ))}
            </div>
        </div>
    );
}
