"use client";
import { useState, useEffect } from "react";
import Image from "next/image";

export default function MultiPicQ({
                                      text,
                                      options,
                                      tag,
                                      questionID,
                                      examAttemptID,
                                      resetSignal,
                                      locked,
                                  }) {
    const [selectedIndex, setSelectedIndex] = useState(null);
    const LOCAL_KEY = "exam_answer";

    // 📥 بررسی پاسخ‌های قبلی
    useEffect(() => {
        const allAnswered = JSON.parse(localStorage.getItem("answered_map")) || {};
        const answeredOptionId = allAnswered[questionID];

        if (answeredOptionId) {
            const idx = options.findIndex((opt) => opt.id === answeredOptionId);
            if (idx !== -1) setSelectedIndex(idx);
            return;
        }

        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, resetSignal]);

    // 🖱 انتخاب پاسخ تصویری
    const handleSelect = (index) => {
        if (locked) return;

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

        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(LOCAL_KEY, 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">
                    {text}
                </p>
                <p className="text-secondary-main text-xl md:text-sm">
                    (این سوال برای سنجش توانایی شما در {tag} می‌باشد)
                </p>
            </div>

            {/* گزینه‌های تصویری */}
            <div className="grid grid-cols-2 md:grid-cols-1 gap-4">
                {options.map((item, index) => (
                    <button
                        key={index}
                        onClick={() => handleSelect(index)}
                        disabled={locked}
                        className={`relative border-2 rounded-2xl overflow-hidden transition-all duration-200
              ${
                            selectedIndex === index
                                ? "border-success-main ring-4 ring-success-lighten"
                                : "border-secondary-main"
                        }
              ${locked ? "opacity-60 cursor-not-allowed" : ""}
            `}
                    >
                        <Image
                            src={item.image || item.image_url}
                            alt={item.text || `گزینه ${index + 1}`}
                            width={400}
                            height={300}
                            className="object-cover w-full h-full"
                        />
                        <div className="absolute bottom-0 left-0 w-full bg-white/80 py-2 text-center font-semibold">
                            {item.text}
                        </div>
                    </button>
                ))}
            </div>
        </div>
    );
}
