"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, { 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 { getClubs } from "@/lib/features/admin/club/service";
import Loading from "../../components/loading";
import { ErrorMessage } from "@/components/ui/error-message";
import { ClubProps } from "@/lib/features/admin/club/type";
import { getSeasons } from "@/lib/features/admin/season/service";
import { SeasonProps } from "@/lib/features/admin/season/type";
import { createStanding } from "@/lib/features/admin/standing/service";
import { StandingFormValidation } from "@/lib/features/admin/standing/schema";

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

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

    // states
    const [clubId, setClubId] = useState('');
    const [seasonId, setSeasonId] = useState('');

    const [gp, setGp] = useState('');
    const [gd, setGd] = useState('');

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

    const queryClient = useQueryClient();

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

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

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

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

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

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

        else {

            setSending(true);

            const body = {
                clubId,
                seasonId,
                gp,
                gd,
                pts
            }

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

            mutation.mutate(body);
        }
    }


    // clubs
    const { data, isLoading, error } = useQuery({
        queryKey: ["club-list-for-new-standing"],
        queryFn: () => getClubs(),
    });


    // seasons
    const { data: seasonData, isLoading: isSeasonLoading, error: errorSeason } = useQuery({
        queryKey: ["season-list-for-new-standing"],
        queryFn: () => getSeasons(),
    });


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


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


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

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

    const clubs: ClubProps[] = data?.data || [];

    const seasons: SeasonProps[] = seasonData?.data || [];


    return (
        <div>
            <div className="text-sm font-medium text-center text-neutral-600 pb-4">
                Create new standing
            </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="clubId"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Club</FormLabel>
                                        <select
                                            className="w-full border border-gray-300 rounded p-2"
                                            value={clubId}
                                            onChange={(e) => setClubId(e.target.value)}
                                        >
                                            <option value=""></option>

                                            {clubs?.length > 0 ? clubs?.map((item) => (
                                                <option key={item?.id} value={item?.id}>
                                                    {item?.name}
                                                </option>
                                            ))
                                                : ""}
                                        </select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


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

                                            {seasons?.length > 0 ? seasons?.map((item) => (
                                                <option key={item?.id} value={item?.id}>
                                                    {item?.name}
                                                </option>
                                            ))
                                                : ""}
                                        </select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


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

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

                            <FormField
                                control={form.control}
                                name="pts"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>PTS</FormLabel>
                                        <FormControl>
                                            <Input type="number" value={pts} onChange={(e) => setPts(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>
    );

}