/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";

import { ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@radix-ui/react-checkbox";

import { DotsHorizontalIcon } from "@radix-ui/react-icons";
import DataTable from "@/components/Table";

import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

import { toast } from "sonner";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import Link from "next/link";
import { ErrorMessage } from "@/components/ui/error-message";
import Loading from "../../components/loading";

import Image from "next/image"
import { Button } from "@/components/ui/button";
import { Eye, LoaderCircle, Pencil, PlusCircle } from "lucide-react";
import { createQuizQuestion, geOneQuiz } from "@/lib/features/admin/quiz/service";
import { QuizProps, QuizQuestionOptionProps, QuizQuestionProps } from "@/lib/features/admin/quiz/type";
import { QuizQuestionFormValidation } from "@/lib/features/admin/quiz/schema";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { ResponseProps } from "@/lib/features/login/type";
import { ErrorResponseProps } from "@/lib/features/admin/account/type";
import Modal from "@/components/modal";
import { UpdateQuizQuestionFormDialog } from "./update-quiz-question-popover";
import { AddQuizQuestionOptionFormDialog } from "./add-quiz-question-option-popover";
import { UpdateQuizQuestionOptionFormDialog } from "./update-quiz-question-option-popover";


interface Props {
    dataId: number;
    onCloseModal: () => void;
    refreshNow: () => void;
}

export const ViewQuizDialog = ({ dataId, onCloseModal, refreshNow }: Props) => {


    const {
        data,
        isLoading,
        error, refetch
    } = useQuery({
        queryKey: ["view-quiz-details"],
        queryFn: () => geOneQuiz(dataId),
    });


    const handleRefresh = () => {
        refetch();
    };


    // view photo states
    const [selectedId, setSelectedId] = useState<number | null>(null);
    const [isViewModalOpen, setViewModalOpen] = useState(false);

    const openViewModal = (id: number) => {
        setSelectedId(id);
        setViewModalOpen(true);
    };

    const closeViewModal = () => {
        setViewModalOpen(false);
        setSelectedId(null);
    };


    /////////////////update question modal
    const [isUpdateModalOpen, setUpdateModalOpen] = useState(false);

    const openUpdateModal = (id: number) => {
        setSelectedId(id);
        setUpdateModalOpen(true);
    };

    const closeUpdateModal = () => {
        setUpdateModalOpen(false);
        setSelectedId(null);
    };


    /////////////////add question option modal
    const [isAddModalOpen, setAddModalOpen] = useState(false);

    const openAddModal = (id: number) => {
        setSelectedId(id);
        setAddModalOpen(true);
    };

    const closeAddModal = () => {
        setAddModalOpen(false);
        setSelectedId(null);
    };


    /////////////////update question option modal
    const [isUpdateOptionModalOpen, setUpdateOptionModalOpen] = useState(false);

    const openUpdateOptionModal = (id: number) => {
        setSelectedId(id);
        setUpdateOptionModalOpen(true);
    };

    const closeUpdateOptionModal = () => {
        setUpdateOptionModalOpen(false);
        setSelectedId(null);
    };


    // Form question setup
    const form = useForm<z.infer<typeof QuizQuestionFormValidation>>({
        resolver: zodResolver(QuizQuestionFormValidation),
        defaultValues: {
        },
    });


    // add question states
    const [desc, setDesc] = useState('');
    const [marks, setMarks] = useState('');

    const [sending, setSending] = useState(false);



    const queryClient = useQueryClient();

    const mutation = useMutation({
        mutationFn: createQuizQuestion,
        onSuccess: (data) => {
            queryClient.invalidateQueries({ queryKey: ["createNewQuizQuestion"] });

            const response = data as unknown as ResponseProps;

            //console.log("Response", response?.data?.message);

            if (response?.data?.message) {
                toast.success(response?.data?.message);

                // refresh details
                handleRefresh();

                // close modal
                onCloseModal();

                //refresh clubs
                refreshNow();

                setSending(false);


            } else {
                toast.error(response?.data?.error);
                setSending(false);
            }

            //window.location.reload();
        },
        onError: (error) => {

            const newError = error as unknown as ErrorResponseProps;
            toast.error(newError?.response?.data?.message);

            return false;
            //window.location.reload();
        },
    });

    function onSubmit() {

        if (desc === null || desc === '') {
            toast.error("Question is required");
            return false;
        }

        else if (marks === null || marks === '') {
            toast.error("Marks is required");
            return false;
        }

        else {

            setSending(true);

            const body = {
                description: desc,
                marks: marks,
                quizId: dataId
            }

            // console.log(JSON.stringify(body));
            // return false;

            mutation.mutate(body);
        }
    }


    console.log(isViewModalOpen, closeViewModal)

    if (isLoading) {
        return <Loading />;
    }


    //////////////////////error handling

    //error
    if (error) {
        return <ErrorMessage error={error} fallback="Dashboard error" />
    }

    // quiz details
    const detail: QuizProps = data?.data?.details || null;


    // questions
    const questions: QuizQuestionProps[] = data?.data?.details?.questions || [];

    //question columns
    const questionColumns: ColumnDef<QuizQuestionProps>[] = [
        {
            id: "select",
            header: ({ table }) => (
                <Checkbox
                    checked={
                        table.getIsAllPageRowsSelected() ||
                        (table.getIsSomePageRowsSelected() && "indeterminate")
                    }
                    onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
                    aria-label="Select all"
                />
            ),
            cell: ({ row }) => (
                <Checkbox
                    checked={row.getIsSelected()}
                    onCheckedChange={(value) => row.toggleSelected(!!value)}
                    aria-label="Select row"
                />
            ),
            enableSorting: false,
            enableHiding: false,
        },

        {
            accessorKey: "description",
            header: () => <div className="text-left table-size">Question</div>,
            cell: ({ row }) => {
                return (
                    <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                        {row.getValue("description")}
                    </div>
                );
            },
        },


        {
            accessorKey: "marks",
            header: () => <div className="text-left table-size">Marks</div>,
            cell: ({ row }) => {
                return (
                    <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                        <b className="text-blue-500">
                            {row.getValue("marks")}
                        </b>
                    </div>
                );
            },
        },

        {
            accessorKey: "options",
            header: () => <div className="text-left table-size">Options</div>,
            cell: ({ row }) => {
                return (
                    <div className="text-left font-normal table-size">
                        {row?.original?.options.map((optionItem: QuizQuestionOptionProps, index) => (
                            <>
                                <p onClick={() => openUpdateOptionModal(optionItem?.id)} className={optionItem?.correct === "1" ? "text-blue-500" : ""}>
                                    {index + 1 + "" + ". " + optionItem?.description}
                                </p>
                                <br />
                            </>
                        ))}
                    </div>
                );
            },
        },


        {
            id: "actions",
            enableHiding: false,
            header: "Actions",
            cell: ({ row }) => {

                return (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-8 w-8 p-0">
                                <span className="sr-only">Open menu</span>
                                <DotsHorizontalIcon className="h-4 w-4" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                            <DropdownMenuSeparator />

                            <DropdownMenuItem onClick={() => openViewModal(row?.original?.id)}>
                                <Eye />
                                View
                            </DropdownMenuItem>


                            <>
                                <DropdownMenuItem onClick={() => openUpdateModal(row?.original?.id)}
                                >
                                    <Pencil className="text-blue-500" />
                                    Update
                                </DropdownMenuItem>

                                <DropdownMenuItem onClick={() => openAddModal(row?.original?.id)}
                                >
                                    <PlusCircle className="text-blue-500" />
                                    Answer
                                </DropdownMenuItem>
                            </>



                        </DropdownMenuContent>
                    </DropdownMenu>
                );
            },
        },
    ];



    return (
        <>

            {/**************** Update quiz question modal ******/}
            <Modal isOpen={isUpdateModalOpen} onClose={closeUpdateModal} size="md">
                <UpdateQuizQuestionFormDialog dataId={Number(selectedId)} onCloseModal={closeUpdateModal} refreshNow={handleRefresh} />
            </Modal>


            {/**************** add quiz question option modal ******/}
            <Modal isOpen={isAddModalOpen} onClose={closeAddModal} size="md">
                <AddQuizQuestionOptionFormDialog dataId={Number(selectedId)} onCloseModal={closeAddModal} refreshNow={handleRefresh} />
            </Modal>

            {/**************** update quiz question option modal ******/}
            <Modal isOpen={isUpdateOptionModalOpen} onClose={closeUpdateOptionModal} size="md">
                <UpdateQuizQuestionOptionFormDialog dataId={Number(selectedId)} onCloseModal={closeUpdateOptionModal} refreshNow={handleRefresh} />
            </Modal>


            <div className="h-auto max-h-[80vh] overflow-y-auto scrollbar-hide">

                <>
                    <div className="overflow-x-auto w-full grid grid-cols-1 gap-4">

                        <fieldset className="pl-2 text-sm font-bold border-4 rounded-[10px] text-neutral-600 pb-4">
                            <legend className="text-blue-700 text-center">
                                Quiz information
                            </legend>

                            <table className="min-w-full viewDetail" >
                                <tbody className="w-full">

                                    <tr style={{ border: 10 }} key={12} className="hover:bg-gray-50 border-2">
                                        <td>
                                            <Image
                                                src={`${detail?.image}`}
                                                alt={detail?.title}
                                                width={200}
                                                height={200}
                                                className="rounded-2xl"
                                            /><br />

                                        </td>
                                    </tr>

                                    <tr style={{ border: 10 }} key={8765} className="hover:bg-gray-50 border-2">
                                        <td>
                                            <b>Title:</b>
                                            <Link href="#">
                                                {" " + detail?.title}
                                            </Link>
                                        </td>
                                    </tr>

                                    <tr style={{ border: 10 }} key={51} className="hover:bg-gray-50 border-2">
                                        <td>
                                            <b>Description:</b>
                                            <Link href="#">
                                                {" " + detail?.description}
                                            </Link>
                                        </td>
                                    </tr>

                                    <tr style={{ border: 10 }} key={2001} className="hover:bg-gray-50 border-2">
                                        <td>
                                            <b>Marks:</b>
                                            <b className="text-blue-800 text-md">
                                                {" " + detail?.marks}
                                            </b>
                                        </td>
                                    </tr>

                                    <tr style={{ border: 10 }} key={2002} className="hover:bg-gray-50 border-2">
                                        <td>
                                            <b>Date:</b>
                                            <Link href="#">
                                                {" " + detail?.date}
                                            </Link>
                                        </td>
                                    </tr>


                                    <tr style={{ border: 10 }} key={2003} className="hover:bg-gray-50 border-2">
                                        <td>
                                            <b>Open:</b>
                                            <Link href="#">
                                                {detail?.open === "1" ?
                                                    <b className="text-green-500">{" YES"}</b>
                                                    :
                                                    <b className="text-red-500">{" NO"}</b>
                                                }
                                            </Link>
                                        </td>
                                    </tr>

                                </tbody>
                            </table>
                        </fieldset>


                        <fieldset className="pl-2 text-sm font-bold border-4 rounded-[10px] text-neutral-600 pb-4">
                            <legend className="text-blue-700 text-center">
                                Add new question
                            </legend>

                            <Form {...form}>
                                <form className="space-y-6">
                                    <div className="grid gap-2">

                                        <div className="grid grid-cols-1 gap-2">

                                            <FormField
                                                control={form.control}
                                                name="description"
                                                render={({ }) => (
                                                    <FormItem>
                                                        <FormLabel>Question</FormLabel>
                                                        <FormControl>
                                                            <Textarea value={desc} onChange={(e) => setDesc(e.target.value)} />
                                                        </FormControl>
                                                        <FormMessage />
                                                    </FormItem>
                                                )}
                                            />

                                            <FormField
                                                control={form.control}
                                                name="marks"
                                                render={({ }) => (
                                                    <FormItem>
                                                        <FormLabel>Marks</FormLabel>
                                                        <FormControl>
                                                            <Input type="number" value={marks} onChange={(e) => setMarks(e.target.value)} />
                                                        </FormControl>
                                                        <FormMessage />
                                                    </FormItem>
                                                )}
                                            />


                                        </div>

                                        <Button className="confirm-button mt-4" type="button" onClick={() => onSubmit()}  >
                                            {sending ?
                                                <LoaderCircle className="animate-spin" />
                                                : "SAVE"
                                            }
                                        </Button>
                                    </div>
                                </form>
                            </Form>

                        </fieldset>


                        {/*************** Questions ************ */}

                        <fieldset className="pl-2 text-sm font-bold border-4 rounded-[10px] text-neutral-600 pb-4">
                            <legend className="text-blue-700 text-center">
                                Questions
                            </legend>
                            <div>
                                <DataTable size={16} columns={questionColumns} data={questions} />
                            </div>
                        </fieldset>



                    </div>




                </>
            </div>
        </>
    );
};