"use client";
import Image from "next/image";
import logo from "../../../../public/icons/logo.svg";
import Container from "../../../components/ui/container/container";
import MultiAnswerQ from "@/app/exam/step2/_component/MultiAnswerQV";
import { IoIosArrowRoundBack, IoIosArrowRoundForward } from "react-icons/io";
import { IoCheckmark } from "react-icons/io5";
import { useEffect, useState } from "react";
import { GET, POST, PUT } from "@/services/axios/resources/resourcesAPI";
import { useParams, useRouter } from "next/navigation";
import MultiPicQ from "@/app/exam/step2/_component/MultiPicQ";
import TextQ from "@/app/exam/step2/_component/TextQ";
import MultiAnswerQV from "@/app/exam/step2/_component/MultiAnswerQV";
import MultiAnswerQH from "@/app/exam/step2/_component/MultiAnswerQH";
import MutiAnswerQS from "@/app/exam/step2/_component/MutiAnswerQS";

export default function Step2() {
    const { id } = useParams();
    const router = useRouter();

    const [sections, setSections] = useState(null);
    const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
    const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
    const [answeredQuestions, setAnsweredQuestions] = useState([]);
    const [answeredMap, setAnsweredMap] = useState({});
    const [resetSignal, setResetSignal] = useState(0);
    const [loading, setLoading] = useState(false);
    const [loadingBtn, setLoadingBtn] = useState(false);
    const [timeLeft, setTimeLeft] = useState(0);
    const [examInfo, setExamInfo] = useState(null);
    const [examName, setExamName] = useState("");

    const TIMER_KEY = "exam_timer";

    // helper: read permission flags (numeric: 1 = permitted, 0 = not permitted)
    const readIsTransferPermitted = () =>
        typeof window !== "undefined"
            ? Number(localStorage.getItem("is_transfer_permitted")) || 0
            : 0;
    const readIsUpdatePermitted = () =>
        typeof window !== "undefined"
            ? Number(localStorage.getItem("is_update_answer_permitted")) || 0
            : 0;

    // 🕒 فرمت تایمر
    const formatTime = (seconds) => {
        const m = Math.floor(seconds / 60);
        const s = seconds % 60;
        return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
    };

    // 📦 گرفتن داده از API
    function getApi(groupId) {
        if (!examInfo) return;
        setLoading(true);
        GET(`api/exam/show-questions/${groupId}`)
            .then((res) => {
                setSections(res.data);
                setCurrentSectionIndex(0);
                setCurrentQuestionIndex(0);

                if (typeof window !== "undefined") {
                    const a = JSON.parse(localStorage.getItem("answered_questions"));
                    setAnsweredQuestions(Array.isArray(a) ? a : []);
                }

                setResetSignal((prev) => prev + 1);

                // 🕒 بررسی تایمر ذخیره‌شده
                if (typeof window !== "undefined") {
                    const stored = JSON.parse(localStorage.getItem(TIMER_KEY));
                    if (!stored || stored.groupId !== groupId) {
                        const initial = res.data.duration * 60;
                        const endTime = Date.now() + initial * 1000;
                        localStorage.setItem(
                            TIMER_KEY,
                            JSON.stringify({ groupId, endTime })
                        );
                        setTimeLeft(initial);
                    } else {
                        const remaining = Math.max(
                            Math.floor((stored.endTime - Date.now()) / 1000),
                            0
                        );
                        setTimeLeft(remaining);
                    }

                    // ذخیره دسترسی‌ها
                    if (res.data.is_transfer_permitted !== undefined) {
                        localStorage.setItem(
                            "is_transfer_permitted",
                            String(Number(res.data.is_transfer_permitted))
                        );
                    }
                    if (res.data.is_update_answer_permitted !== undefined) {
                        localStorage.setItem(
                            "is_update_answer_permitted",
                            String(Number(res.data.is_update_answer_permitted))
                        );
                    }
                }
            })
            .catch(console.error)
            .finally(() => setLoading(false));
    }

    useEffect(() => {
        if (typeof window !== "undefined") {
            const storedExamInfo = JSON.parse(localStorage.getItem("exam_info"));
            setExamInfo(storedExamInfo);
            const storedName = localStorage.getItem("examName");
            setExamName(storedName || "");
        }
    }, []);

    useEffect(() => {
        if (examInfo) {
            getApi(examInfo.time_group_attempt_id);
        }
    }, [examInfo]);

    // ⏱️ تایمر
    useEffect(() => {
        if (timeLeft <= 0) return;

        const interval = setInterval(() => {
            setTimeLeft((prev) => {
                if (prev <= 1) {
                    clearInterval(interval);
                    handleFinishGroup(); // پایان آزمون خودکار
                    return 0;
                }

                // ذخیره زمان جدید
                if (typeof window !== "undefined") {
                    const stored = JSON.parse(localStorage.getItem(TIMER_KEY));
                    if (stored) {
                        const newEnd = Date.now() + (prev - 1) * 1000;
                        localStorage.setItem(
                            TIMER_KEY,
                            JSON.stringify({ ...stored, endTime: newEnd })
                        );
                    }
                }

                return prev - 1;
            });
        }, 1000);

        return () => clearInterval(interval);
    }, [timeLeft]);

    const currentSection = sections?.sections?.[currentSectionIndex];
    const currentQuestion = currentSection?.questions?.[currentQuestionIndex];

    const markQuestionAnswered = (questionId, optionId) => {
        setAnsweredQuestions((prev) => {
            const next = Array.from(new Set([...prev, questionId]));
            if (typeof window !== "undefined")
                localStorage.setItem("answered_questions", JSON.stringify(next));
            return next;
        });

        setAnsweredMap((prev) => {
            const updated = { ...prev, [questionId]: optionId };
            if (typeof window !== "undefined")
                localStorage.setItem("answered_map", JSON.stringify(updated));
            return updated;
        });
    };

    // 🧭 تغییر سوال
    function handleMove(direction) {
        if (!currentSection) return;
        if (typeof window === "undefined") return;

        const examAnswer = JSON.parse(localStorage.getItem("exam_answer"));
        const examInfoLocal = JSON.parse(localStorage.getItem("exam_info"));
        const total = currentSection?.questions?.length || 0;

        const isTransferPermitted = readIsTransferPermitted();
        const isUpdatePermitted = readIsUpdatePermitted();

        if (isTransferPermitted === 0 && direction === "prev") return;

        let nextIndex =
            direction === "next"
                ? currentQuestionIndex + 1
                : currentQuestionIndex - 1;

        if (direction === "prev") {
            if (nextIndex < 0) nextIndex = 0;
            setCurrentQuestionIndex(nextIndex);
            return;
        }

        if (nextIndex < total) {
            if (!examAnswer) {
                setCurrentQuestionIndex(nextIndex);
                return;
            }

            if (
                answeredQuestions.includes(examAnswer.question_id) &&
                isUpdatePermitted === 0
            ) {
                localStorage.removeItem("exam_answer");
                setResetSignal((prev) => prev + 1);
                setCurrentQuestionIndex(nextIndex);
                return;
            }

            setLoadingBtn(true);
            POST("api/exam/register-answers", {
                question_option_id: examAnswer.question_option_id,
                question_id: examAnswer.question_id,
                exam_attempt_id: examInfoLocal.exam_attempt_id,
            })
                .then((res) => {
                    markQuestionAnswered(
                        examAnswer.question_id,
                        examAnswer.question_option_id
                    );
                    localStorage.removeItem("exam_answer");
                    setResetSignal((prev) => prev + 1);
                    setCurrentQuestionIndex(nextIndex);
                })
                .catch((err) => console.error("Error registering answer:", err))
                .finally(() => setLoadingBtn(false));

            return;
        }

        const lastSectionIndex = (sections?.sections?.length || 1) - 1;
        if (currentSectionIndex < lastSectionIndex) {
            const targetSectionIndex = currentSectionIndex + 1;
            const targetQuestionIndex = 0;

            if (!examAnswer) {
                setCurrentSectionIndex(targetSectionIndex);
                setCurrentQuestionIndex(targetQuestionIndex);
                setResetSignal((prev) => prev + 1);
                return;
            }

            if (
                answeredQuestions.includes(examAnswer.question_id) &&
                isUpdatePermitted === 0
            ) {
                localStorage.removeItem("exam_answer");
                setResetSignal((prev) => prev + 1);
                setCurrentSectionIndex(targetSectionIndex);
                setCurrentQuestionIndex(targetQuestionIndex);
                return;
            }

            setLoadingBtn(true);
            POST("api/exam/register-answers", {
                question_option_id: examAnswer.question_option_id,
                question_id: examAnswer.question_id,
                exam_attempt_id: examInfoLocal.exam_attempt_id,
            })
                .then(() => {
                    markQuestionAnswered(examAnswer.question_id);
                    localStorage.removeItem("exam_answer");
                    setResetSignal((prev) => prev + 1);
                    setCurrentSectionIndex(targetSectionIndex);
                    setCurrentQuestionIndex(targetQuestionIndex);
                })
                .catch((err) => console.error("Error registering answer:", err))
                .finally(() => setLoadingBtn(false));

            return;
        }
    }

    // ✅ اتمام گروه
    function handleFinishGroup() {
        if (!sections) return;
        if (typeof window === "undefined") return;

        const payload = {
            time_group_attempt_id: sections.time_group_attempt_id,
        };
        const examInfoLocal = JSON.parse(localStorage.getItem("exam_info"));

        PUT(`/api/exam/update-result/${sections.time_group_attempt_id}`, payload)
            .then((res) => {
                localStorage.removeItem(TIMER_KEY);

                const data = res;
                const updatedExamInfo = {
                    ...examInfoLocal,
                    time_group_attempt_id: data.next_time_group_attempt_id,
                    time_group_id: data.next_time_group_id,
                };
                localStorage.setItem("exam_info", JSON.stringify(updatedExamInfo));

                localStorage.removeItem("answered_questions");
                setAnsweredQuestions([]);

                if (!data.exam_completed) {
                    getApi(data.next_time_group_attempt_id);
                } else {
                    router.push("/exam/step3");
                }
            })
            .catch((err) => console.error("❌ Error finishing group:", err));
    }

    return (
        <Container className="bg-primary-lighten min-h-[100vh] justify-between text-secondary-main flex flex-col gap-12 pt-8 pb-16 md:px-6 md:pt-10">
            {/* 🧭 Header */}
            <div className="flex items-center justify-between md:flex-col md:gap-4">
                <div className="flex gap-2 items-center justify-evenly">
                    <Image src={logo} alt="logo" width={34} />
                    <p className="font-black text-t2 md:text-body border-b-2 border-secondary-main text-secondary-main">
                        {examName || "در حال بارگذاری..."}
                    </p>
                </div>
                <div className="bg-secondary-main text-white px-4 py-3 rounded-lg font-extrabold text-lg md:text-sm">
                    زمان باقی مانده {formatTime(timeLeft)}
                </div>
            </div>

            {/* 🧩 سوال فعلی */}
            <div className="grid gap-8">
                {currentQuestion ? (
                    (() => {
                        const isUpdatePermitted = readIsUpdatePermitted();
                        const locked =
                            answeredQuestions.includes(currentQuestion.id) &&
                            isUpdatePermitted === 0;

                        if (currentQuestion.lay_out_model === "square") {
                            return (
                                <MutiAnswerQS
                                    key={currentQuestion.id}
                                    questionID={currentQuestion.id}
                                    text={currentQuestion.text}
                                    tag={currentQuestion.tag}
                                    options={currentQuestion.options}
                                    examAttemptID={examInfo?.exam_attempt_id}
                                    resetSignal={resetSignal}
                                    locked={locked}
                                    selectedOptionID={answeredMap[currentQuestion.id]}
                                />
                            );
                        }

                        if (currentQuestion.lay_out_model === "vertical") {
                            return (
                                <MultiAnswerQV
                                    key={currentQuestion.id}
                                    questionID={currentQuestion.id}
                                    text={currentQuestion.text}
                                    tag={currentQuestion.tag}
                                    options={currentQuestion.options}
                                    examAttemptID={examInfo?.exam_attempt_id}
                                    resetSignal={resetSignal}
                                    locked={locked}
                                    selectedOptionID={answeredMap[currentQuestion.id]}
                                />
                            );
                        }

                        if (currentQuestion.lay_out_model === "horizontal") {
                            return (
                                <MultiAnswerQH
                                    key={currentQuestion.id}
                                    questionID={currentQuestion.id}
                                    text={currentQuestion.text}
                                    tag={currentQuestion.tag}
                                    options={currentQuestion.options}
                                    examAttemptID={examInfo?.exam_attempt_id}
                                    resetSignal={resetSignal}
                                    locked={locked}
                                    selectedOptionID={answeredMap[currentQuestion.id]}
                                />
                            );
                        }

                        return <TextQ />;
                    })()
                ) : (
                    <p className="text-center text-muted">در حال بارگذاری سؤالات...</p>
                )}
            </div>

            <div>
                {/* 🧱 سکشن‌ها */}
                {sections?.sections && (
                    <div className="flex flex-wrap gap-4 mb-4 sm:grid sm:grid-cols-2">
                        {sections.sections.map((section, index) => {
                            const isActive = index === currentSectionIndex;
                            return (
                                <button
                                    key={index}
                                    onClick={() => {
                                        const isTransferPermitted = readIsTransferPermitted();
                                        if (isTransferPermitted === 0) return; // جلوگیری از تغییر سکشن در حالت غیرفعال
                                        setCurrentSectionIndex(index);
                                        setCurrentQuestionIndex(0);
                                    }}
                                    className={`flex items-center border-2 text-lg font-extrabold px-5 py-4 rounded-xl md:text-sm md:font-bold md:p-3 sm:justify-center transition-all
                                    ${
                                        isActive
                                            ? "bg-info-main border-info-main text-white"
                                            : "bg-white border-secondary-main text-secondary-main hover:bg-info-lighten"
                                    }`}>
                                    {section.title}
                                </button>
                            );
                        })}
                    </div>
                )}

                {/* 🔢 شماره سوالات */}
                {currentSection && (
                    <div className="border-2 bg-white border-primary-main rounded-xl py-7 px-6 grid gap-6">
                        <div className="flex flex-wrap gap-2 sm:gap-4">
                            {sections?.sections?.flatMap((section) => section.questions).map((q, index) => {
                                const isAnswered = answeredQuestions.includes(q.id);

                                // پیدا کردن سکشن فعلی و اندیس سؤال داخل اون
                                const sectionIndex = sections.sections.findIndex(s =>
                                    s.questions.some(qq => qq.id === q.id)
                                );
                                const questionIndexInSection = sections.sections[sectionIndex].questions.findIndex(qq => qq.id === q.id);

                                const isCurrent =
                                    sectionIndex === currentSectionIndex &&
                                    questionIndexInSection === currentQuestionIndex;

                                return (
                                    <button
                                        key={q.id}
                                        onClick={() => {
                                            const isTransferPermitted = readIsTransferPermitted();
                                            if (isTransferPermitted === 0) return; // جلوگیری از پرش در حالت غیرفعال
                                            setCurrentSectionIndex(sectionIndex);
                                            setCurrentQuestionIndex(questionIndexInSection);
                                        }}
                                        className={`flex items-center justify-center rounded-lg border-2 px-4 py-2 font-bold transition-all
                                                ${
                                            isAnswered
                                                ? "bg-success-main border-success-main text-white"
                                                : isCurrent
                                                    ? "bg-info-main border-info-main text-white"
                                                    : "border-secondary-main text-secondary-main bg-white"
                                        }`}
                                    >
                                        <span className="w-4">{index + 1}</span>
                                    </button>
                                );
                            })}
                        </div>

                        {/* 🎛 کنترل‌ها */}
                        <div className="flex items-center justify-between md:flex-col md:text-sm md:gap-4 mt-5">
                            <div className="flex items-center gap-5 md:w-full sm:flex-col">
                                <p className="flex items-center gap-2">
                                    <span
                                        className="bg-success-main w-5 h-5 border border-secondary-main rounded"></span>
                                    پاسخ داده شده
                                </p>
                                <p className="flex items-center gap-2">
                                    <span className="bg-info-main w-5 h-5 border border-secondary-main rounded"></span>
                                    سوال در حال پاسخ
                                </p>
                                <p className="flex items-center gap-2">
                                    <span className="border border-secondary-main w-5 h-5 rounded"></span>
                                    پاسخ داده نشده
                                </p>
                            </div>

                            <div className="flex gap-3 font-bold md:justify-center sm:grid sm:grid-cols-2 sm:gap-2">
                                <button
                                    onClick={() => handleMove("prev")}
                                    disabled={currentQuestionIndex === 0 || loadingBtn || readIsTransferPermitted() === 0}
                                    className="flex items-center p-3 bg-secondary-main rounded-lg md:py-1.5 md:px-1 disabled:opacity-50 text-white"
                                >
                                    <IoIosArrowRoundForward size={30}/>
                                    سوال قبلی
                                </button>

                                <button
                                    onClick={() => handleMove("next")}
                                    disabled={loadingBtn}
                                    className={`flex items-center p-3 bg-info-main rounded-lg md:py-1.5 md:px-1 text-white transition-all ${
                                        loadingBtn ? "opacity-50 cursor-not-allowed" : "hover:bg-info-dark"
                                    }`}
                                >
                                    سوال بعدی
                                    <IoIosArrowRoundBack size={30}/>
                                </button>

                                <button
                                    onClick={handleFinishGroup}
                                    className="flex items-center justify-center p-3 bg-success-main rounded-lg md:py-1.5 md:px-1 sm:col-span-2 sm:p-3 text-white"
                                >
                                    مرحله بعدی
                                </button>
                            </div>
                        </div>
                    </div>
                )}

            </div>
        </Container>
    );
}
