/* 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 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, Pencil, PlusCircle } from "lucide-react";

import Modal from "@/components/modal";
import { UpdateVoteOptionFormDialog } from "./update-vote-option-popover";
import { AddVoteOptionFormDialog } from "./add-vote-option-popover";
import { geOnePrediction } from "@/lib/features/admin/prediction/service";
import { PredictionCommentProps, PredictionProps } from "@/lib/features/admin/prediction/type";


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

export const ViewPredictionDialog = ({ dataId }: Props) => {


    const {
        data,
        isLoading,
        error, refetch
    } = useQuery({
        queryKey: ["view-prediction-details"],
        queryFn: () => geOnePrediction(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);
    };

    console.log(isViewModalOpen, closeViewModal)

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


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

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

    // prediction details
    const detail: PredictionProps = data?.data?.details || null;


    // predictions
    const predictions: PredictionCommentProps[] = data?.data?.details?.predictions || [];

    //prediction columns
    const predictionColumns: ColumnDef<PredictionCommentProps>[] = [
        {
            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: "tbl_userFname",
            header: () => <div className="text-left table-size">User</div>,
            cell: ({ row }) => {
                return (
                    <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                        {row.getValue("tbl_userFname") + ' ' + row?.original?.tbl_userLname}
                    </div>
                );
            },
        },

        {
            accessorKey: "description",
            header: () => <div className="text-left table-size">Comment</div>,
            cell: ({ row }) => {
                return (
                    <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                        <b>{row.getValue("description")}</b>
                    </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: "date",
            header: () => <div className="text-left table-size">Date</div>,
            cell: ({ row }) => {
                return (
                    <div className="text-left font-normal table-size" onClick={() => openViewModal(row?.original?.id)}>
                        {row.getValue("date")}
                    </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>

                            </>



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



    return (
        <>

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


            {/**************** add vote option modal ******/}
            <Modal isOpen={isAddModalOpen} onClose={closeAddModal} size="md">
                <AddVoteOptionFormDialog dataId={Number(selectedId)} onCloseModal={closeAddModal} 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">
                                Vote 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>Predicted:</b>
                                            <b className="text-blue-800 text-md">
                                                {" " + detail?.predicted}
                                            </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>


                        {/*************** Predictions ************ */}

                        <fieldset className="pl-2 text-sm font-bold border-4 rounded-[10px] text-neutral-600 pb-4">
                            <legend className="text-blue-700 text-center">
                                Predictions
                            </legend>
                            <Link onClick={() => openAddModal(dataId)} href="#" className="float-right text-blue-500">
                                <PlusCircle />
                            </Link>
                            <div>
                                <DataTable size={16} columns={predictionColumns} data={predictions} />
                            </div>
                        </fieldset>



                    </div>




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