"use client";

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

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

import React, { useEffect, useState } from "react";
import { ErrorResponseProps } from "@/lib/features/admin/account/type";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { LoaderCircle } from "lucide-react";
import { ResponseProps } from "@/lib/features/login/type";
import { ErrorMessage } from "@/components/ui/error-message";
import Loading from "../../components/loading";
import { Textarea } from "@/components/ui/textarea";
import { geOneVote, updateVote } from "@/lib/features/admin/vote/service";
import { VoteFormValidation } from "@/lib/features/admin/vote/schema";

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

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

    // states
    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

    const [image, setImage] = useState('');
    const [status, setStatus] = useState('');

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


    // vote details
    const {
        data,
        isLoading,
        error
    } = useQuery({
        queryKey: ["view-vote-details-for-update"],
        queryFn: () => geOneVote(dataId),
    });


    // Update states
    useEffect(() => {
        if (data?.data?.details) {
            setTitle(data?.data?.details?.title)
            setDesc(data?.data?.details?.description);

            setImage(data?.data?.details?.image);
            setStatus(data?.data?.details?.status);

            setOpen(data?.data?.details?.open);

        }

    }, [data]);



    const queryClient = useQueryClient();

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

            const response = data as unknown as ResponseProps;

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

                // close modal
                onCloseModal();

                //refresh clubs
                refreshNow();

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

            //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 (title === null || title === '') {
            toast.error("Title is required");
            return false;
        }

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

        else if (image === null || image === '') {
            toast.error("Image url is required");
            return false;
        }

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


        else if (open === null || open === '') {
            toast.error("Is it open?");
            return false;
        }

        else {

            setSending(true);

            const body = {
                title: title,
                description: desc,
                image: image,

                status: status,
                open: open,
                voteId: dataId
            }

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

            mutation.mutate(body);
        }
    }



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


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


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

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



    return (
        <div>
            <div className="text-sm font-medium text-center text-neutral-600 pb-4">
                Update vote
            </div>

            <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="title"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Title</FormLabel>
                                        <FormControl>
                                            <Input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

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

                            <FormField
                                control={form.control}
                                name="image"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Image</FormLabel>
                                        <FormControl>
                                            <Input type="text" value={image} onChange={(e) => setImage(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <FormField
                                control={form.control}
                                name="open"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Open</FormLabel>
                                        <select
                                            className="w-full border border-gray-300 rounded p-2"
                                            value={open}
                                            onChange={(e) => setOpen(e.target.value)}
                                        >
                                            <option value=""></option>

                                            <option key="1" value="1">Yes</option>
                                            <option key="0" value="0" className="text-red-500">No</option>
                                        </select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <FormField
                                control={form.control}
                                name="status"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Status</FormLabel>
                                        <select
                                            className="w-full border border-gray-300 rounded p-2"
                                            value={status}
                                            onChange={(e) => setStatus(e.target.value)}
                                        >
                                            <option value=""></option>

                                            <option key="1" value="1">Active</option>
                                            <option key="0" value="0" className="text-red-500">Remove</option>
                                        </select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                        </div>

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

}