"use client";

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

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

import React, { 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 { Button } from "@/components/ui/button";
import { LoaderCircle } from "lucide-react";
import { ResponseProps } from "@/lib/features/login/type";
import { Textarea } from "@/components/ui/textarea";
import { createVoteOption } from "@/lib/features/admin/vote/service";
import { VoteOptionFormValidation } from "@/lib/features/admin/vote/schema";

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

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

    // states
    const [desc, setDesc] = useState('');
    const [sending, setSending] = useState(false);


    const queryClient = useQueryClient();

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

            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);
            }

            setSending(false);

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

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

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

    function onSubmit() {

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

        else {

            setSending(true);

            const body = {
                description: desc,
                voteId: dataId
            }

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

            mutation.mutate(body);
        }
    }



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



    return (
        <div>
            <div className="text-sm font-medium text-center text-neutral-600 pb-4">
                Add new option
            </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="description"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Option</FormLabel>
                                        <FormControl>
                                            <Textarea value={desc} onChange={(e) => setDesc(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>
        </div>
    );

}