"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 { geOneFixture, updateFixture } from "@/lib/features/admin/fixture/service";
import { FixtureFormValidation } from "@/lib/features/admin/fixture/schema";
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";

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

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

    // states
    const [visitorId, setVisitorId] = useState('');
    const [seasonId, setSeasonId] = useState('');

    const [receiverId, setReceiverId] = useState('');
    const [date, setDate] = useState('');

    const [hour, setHour] = useState('');
    const [awayGoals, setAwayGoals] = useState('');

    const [homeGoals, setHomeGoals] = useState('');
    const [video, setVideo] = useState('');

    const [status, setStatus] = useState('1');
    const [finished, setFinished] = useState('');

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


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


    // Update states
    useEffect(() => {
        if (data?.data?.details) {
            setVisitorId(data?.data?.details?.visitorId);
            setReceiverId(data?.data?.details?.receiverId);

            setSeasonId(data?.data?.details?.seasonId);
            setDate(data?.data?.details?.date);

            setHour(data?.data?.details?.hour);
            setStatus(data?.data?.details?.status);

            setHomeGoals(data?.data?.details?.receiverGoals);
            setAwayGoals(data?.data?.details?.visitorGoals);

            setFinished(data?.data?.details?.finished);
            setVideo(data?.data?.details?.video);

        }

    }, [data]);


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


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




    const queryClient = useQueryClient();

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

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

        else if (receiverId === null || receiverId === '') {
            toast.error("Home team is required");
            return false;
        }

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

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

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

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

        else {

            setSending(true);

            const body = {
                visitorId: visitorId,
                receiverId: receiverId,
                seasonId: seasonId,

                date: date,
                hour: hour,

                status: status,
                fixtureId: dataId,

                homeGoals: homeGoals,
                awayGoals: awayGoals,

                video: video,
                finished: finished
            }

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

            mutation.mutate(body);
        }
    }



    // Form setup
    const form = useForm<z.infer<typeof FixtureFormValidation>>({
        resolver: zodResolver(FixtureFormValidation),
        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 fixture
            </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="receiverId"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Home team</FormLabel>
                                        <select
                                            className="w-full border border-gray-300 rounded p-2"
                                            value={receiverId}
                                            onChange={(e) => setReceiverId(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="visitorId"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Away team</FormLabel>
                                        <select
                                            className="w-full border border-gray-300 rounded p-2"
                                            value={visitorId}
                                            onChange={(e) => setVisitorId(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="date"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Date</FormLabel>
                                        <FormControl>
                                            <Input type="date" value={date} onChange={(e) => setDate(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="hour"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Hour</FormLabel>
                                        <FormControl>
                                            <Input type="time" value={hour} onChange={(e) => setHour(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <FormField
                                control={form.control}
                                name="finished"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Finished</FormLabel>
                                        <select
                                            className="w-full border border-gray-300 rounded p-2"
                                            value={finished}
                                            onChange={(e) => setFinished(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>
                                )}
                            />

                            {finished === "1" ?

                                <>
                                    <FormField
                                        control={form.control}
                                        name="homeGoals"
                                        render={({ }) => (
                                            <FormItem>
                                                <FormLabel>Home goals</FormLabel>
                                                <FormControl>
                                                    <Input type="number" value={homeGoals} onChange={(e) => setHomeGoals(e.target.value)} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="awayGoals"
                                        render={({ }) => (
                                            <FormItem>
                                                <FormLabel>Away goals</FormLabel>
                                                <FormControl>
                                                    <Input type="number" value={awayGoals} onChange={(e) => setAwayGoals(e.target.value)} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="video"
                                        render={({ }) => (
                                            <FormItem>
                                                <FormLabel>Video</FormLabel>
                                                <FormControl>
                                                    <Input type="text" value={video} onChange={(e) => setVideo(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>
    );

}