"use client"
import Container from "@/components/ui/container/container";
import Image from "next/image";
import logo from "../../../../../public/icons/logo.svg";
import {useEffect, useState} from "react";
import {GET, POST} from "@/services/axios/resources/resourcesAPI";
import {useParams} from "next/navigation";
import {useRouter} from "next/navigation";


export default function Step1() {

    const [examData, setExamData] = useState("");
    const [sections, setSections] = useState([]);
    const [timeGroups, setTimeGroups] = useState([]);

    const {id} = useParams();

    const router = useRouter();

    function getApi() {

        GET(`/api/admin/exam-management/exams/show/${id}`)
            .then(res => {
                setExamData(res.data);
                setSections(res.data.sections);
                console.log(res.data.sections);
                setTimeGroups(res.data.time_groups);
                localStorage.setItem("is_transfer_permitted", JSON.stringify(res.data.is_transfer_permitted));
                localStorage.setItem("is_update_answer_permitted", JSON.stringify(res.data.is_update_answer_permitted));
            })
    }


    function handleStartExam() {

        const payload = {
            exam_id: id,
            user_id: 2,
        }
        POST(`/api/exam/start`, payload)
            .then((res) => {
                localStorage.setItem("exam_info", JSON.stringify(res));
                localStorage.setItem("section", JSON.stringify(sections));
                localStorage.setItem("examName", JSON.stringify(examData.title));

                router.push(`/exam/step2`);
            })
    }

    useEffect(() => {
        getApi();
    }, [])


    return (
        <Container
            className="bg-primary-lighten min-h-[100vh] text-secondary-main flex flex-col justify-center gap-12 md:px-6 py-12">

            <div className="flex gap-2 items-center justify-center sm: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">

                    {examData.title}</p>

            </div>

            <p className="text-center text-t2 font-medium leading-[55px] md:text-lg md:text-justify">
                 سلام محمدمهدی ایمنی عزیز
                 {examData.description}
            </p>

            <div className="w-full overflow-x-auto rounded-lg">
                <table className="text-lg md:text-sm min-w-[700px] mx-auto border-collapse">
                    <thead className="bg-gray-100">
                    <tr className="bg-white">
                        <td className="px-4 py-2 border-b border-gray-300 rounded-tr-lg text-primary-main bg-black whitespace-nowrap">
                            ردیف
                        </td>
                        <td className="p-0 border-0 whitespace-nowrap">
                            <div className="px-4 py-2 bg-primary-main text-secondary-main">
                                سر فصل های آزمون
                            </div>
                        </td>
                        <td className="px-4 py-2 border-b border-gray-300 text-primary-main bg-black whitespace-nowrap">
                            ضریب
                        </td>
                        <td className="px-4 py-2 border-b border-gray-300 bg-primary-main text-secondary-main whitespace-nowrap">
                            تعداد سوال
                        </td>
                        <td className="px-4 py-2 border-b border-gray-300 rounded-tl-lg text-primary-main bg-black whitespace-nowrap">
                            مدت زمان
                        </td>
                    </tr>
                    </thead>
                    <tbody>
                    {sections.map((row, index) => {
                        // بررسی اینکه question_count وجود داره و طولش بیشتر از صفره
                        const totalCount = row.question_count?.length
                            ? row.question_count.reduce((sum, item) => sum + Number(item.count) , 0)
                            : null;

                        // if (examData.time_groups[0].id !== row.exam_time_group_id) {return}
                        return (
                            <tr
                                key={index}
                                className={`${
                                    index % 2 === 0 ? `bg-secondary-lighten` : `bg-white`
                                }`}
                            >
                                <td
                                    className={`px-4 py-2 whitespace-nowrap ${
                                        index === sections.length -1 && "rounded-br-lg"
                                    }`}
                                >
                                    {row.order}
                                </td>
                                <td className="px-4 py-2 whitespace-nowrap">{row.title}</td>
                                <td className="px-4 py-2 whitespace-nowrap">{row.weight}</td>
                                <td className="px-4 py-2 whitespace-nowrap">
                                    {totalCount ?? ""}
                                </td>
                                <td
                                    className={`px-4 py-2 whitespace-nowrap ${
                                        index === sections.length -1 && "rounded-bl-lg"
                                    }`}
                                >
                                    {timeGroups[0].duration}
                                </td>
                            </tr>
                        );
                    })}


                    </tbody>
                </table>
            </div>

            <div className="text-danger-main text-t2 font-medium text-center md:text-lg">
                این آزمون نمره منفی دارد به این معنای که هر {examData !== "" && examData?.wrong_to_burn_role[0]} پاسخ اشتباه {examData !== "" && examData?.wrong_to_burn_role[1]} پاسخ صحیح را از بین میبرد!
            </div>

            <div className="mx-auto">
                <button
                    onClick={handleStartExam}
                    className="py-2 px-32 bg-success-main text-white text-t2 font-medium rounded-lg md:text-t3 md:px-24 sm:px-16 sm:py-4"
                >
                    شروع آزمون
                </button>
            </div>
        </Container>
    );
}
