import React, { useState } from "react";
import UserLayout from "./Layout/UserLayout";
import Swal from "sweetalert2";

const Quiz = (props) => {
    const [data, setData] = useState(props.data);
    const [page, setPage] = useState(1);
    const limit = 5;
    const totalPage = Math.ceil(data.length / limit);
    const [selectedAnswer, setSelectedAnswer] = useState({});

    const state = {
        selectedAnswer,
        setSelectedAnswer,
    };

    const handleSubmit = async () => {
        let nilai = 0;
        let totalBenar = 0;
        let totalSalah = 0;

        data.forEach((item) => {
            item.jawaban.forEach((jawaban) => {
                if (jawaban.benar === 1) {
                    if (selectedAnswer[item.id] === jawaban.id) {
                        nilai += 1;
                        totalBenar += 1;
                    } else {
                        totalSalah += 1;
                    }
                }
            });
        });

        nilai = (nilai / data.length) * 100;

        const jawaban = Object.entries(selectedAnswer).map(([key, value]) => ({
            kuis_id: key,
            jawaban_id: value,
        }));

        try {
            const response = await fetch(`/api/v1/quiz/submit`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    materi_id: props.materi_id,
                    user_id: props.auth.id,
                    jawaban: jawaban,
                    nilai: nilai,
                    total_benar: totalBenar,
                    total_salah: totalSalah,
                }),
            });

            const responseData = await response.json();

            Swal.fire({
                title: "Nilai Anda",
                text: `Nilai anda adalah ${nilai}`,
                imageUrl: "/assets/images/overlay3.png",
                imageWidth: 400,
                customClass: {
                    image: "object-cover",
                },
                imageHeight: 200,
                imageAlt: "Custom image",
                confirmButtonText: "Ok",
            }).then(() => {
                location.href = "/user/";
            });
        } catch (error) {
            console.error("Error submitting quiz:", error);
            // Handle error condition, if needed
        }
    };

    return (
        <UserLayout showBack={true} title={"Quiz"} showNavbar={false}>
            <div className="flex flex-col gap-3 mt-3">
                {data
                    .slice((page - 1) * limit, page * limit)
                    .map((item, index) => (
                        <CardSoal
                            key={index}
                            no={(page - 1) * limit + index + 1}
                            pertanyaan={item.pertanyaan} // Perbaikan: Menggunakan item.pertanyaan untuk menampilkan pertanyaan
                            gambar={item.gambar_soal}
                            jawaban={item.jawaban}
                            state={state}
                        />
                    ))}
                <div className="flex flex-row items-center gap-2">
                    {page > 1 && (
                        <button
                            onClick={() => setPage(page - 1)}
                            className="btn btn-primary mt-6 mb-4 flex-1"
                        >
                            Previous
                        </button>
                    )}
                    {page < totalPage && (
                        <button
                            onClick={() => setPage(page + 1)}
                            className="btn btn-primary mt-6 mb-4 flex-1"
                        >
                            Next
                        </button>
                    )}
                    {page === totalPage && (
                        <button
                            onClick={handleSubmit}
                            className="btn btn-primary mt-6 mb-4 flex-1"
                        >
                            Submit
                        </button>
                    )}
                </div>
            </div>
        </UserLayout>
    );
};

const CardSoal = ({ no, pertanyaan, gambar, jawaban, state }) => {
    return (
        <div className="flex flex-col p-4 border-2 rounded-md shadow-md gap-3 bg-white/90">
            <div className="flex flex-col">
                <h1 className="font-bold text-blue-800">No {no}</h1>
                <p className="mt-2">{pertanyaan}</p>
                {gambar &&
                    gambar !== "" &&
                    gambar !== null &&
                    gambar !== "undefined" && (
                        <div className="flex flex-col relative items-start rounded-md justify-start mt-4 min-h-[200px]">
                            <img
                                className="absolute w-full max-w-[200px] h-full object-cover"
                                src={`/uploads/soal/${gambar}`}
                                alt="Gambar Soal"
                                onLoad={(e) => {
                                    e.target.style.display = "block";
                                }}
                                onError={(e) => {
                                    e.target.style.display = "none";
                                }}
                            />
                        </div>
                    )}
                <div className="space-y-2">
                    {jawaban.map((item, index) => (
                        <CardJawaban state={state} item={item} key={index} />
                    ))}
                </div>
            </div>
        </div>
    );
};

const CardJawaban = ({ item, state }) => {
    return (
        <label className="flex flex-row gap-4  rounded-md px-2 my-2" htmlFor="">
            <div className="py-4">
                <input
                    type="radio"
                    name={item.kuis_id}
                    checked={state.selectedAnswer[item.kuis_id] == item.id}
                    onChange={(e) => {
                        state.setSelectedAnswer({
                            ...state.selectedAnswer,
                            [item.kuis_id]: item.id,
                        });
                    }}
                    className="radio radio-info"
                />
            </div>
            <div className="flex flex-col w-full">
                <div className="mt-4">{item.jawaban}</div>
                {item.gambar_jawaban &&
                    item.gambar_jawaban != "" &&
                    item.gambar_jawaban != null && (
                        <div className="flex flex-col relative items-start rounded-md justify-start mt-4 min-h-[200px]">
                            <img
                                className="absolute w-full max-w-[200px] h-full object-cover"
                                src={`/uploads/jawaban/${item.gambar_jawaban}`}
                                alt="Jawaban"
                                onLoad={(e) => {
                                    e.target.style.display = "block";
                                }}
                                onError={(e) => {
                                    e.target.style.display = "none";
                                }}
                            />
                        </div>
                    )}
            </div>
        </label>
    );
};

export default Quiz;
