"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 { getClubs } from "@/lib/features/admin/club/service";
import { getSeasons } from "@/lib/features/admin/season/service";
import { ClubProps } from "@/lib/features/admin/club/type";
import { SeasonProps } from "@/lib/features/admin/season/type";
import { geOneStanding, updateStanding } from "@/lib/features/admin/standing/service";
import { StandingFormValidation } from "@/lib/features/admin/standing/schema";

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

export const UpdateStandingFormDialog = ({ dataId, 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 [status, setStatus] = useState('1');

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


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


    // Update states
    useEffect(() => {
        if (data?.data?.details) {
            setClubId(data?.data?.details?.clubId);
            setSeasonId(data?.data?.details?.seasonId);

            setGp(data?.data?.details?.gp);
            setGd(data?.data?.details?.gd);

            setPts(data?.data?.details?.pts);
            setStatus(data?.data?.details?.status);

        }

    }, [data]);


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


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




    const queryClient = useQueryClient();

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

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

        else {

            setSending(true);

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

                status: status,
                standingId: dataId
            }

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

            mutation.mutate(body);
        }
    }



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


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


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

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


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

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


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




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

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

                        <div className="grid grid-cols-2 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>
                                )}
                            />


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

}