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

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

export const FixtureFormDialog = ({ 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 [sending, setSending] = useState(false);

    const queryClient = useQueryClient();

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

            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 (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 {

            setSending(true);

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

                date: date,
                hour: hour
            }

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

            mutation.mutate(body);
        }
    }


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


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


    // Form setup
    const form = useForm<z.infer<typeof FixtureFormValidation>>({
        resolver: zodResolver(FixtureFormValidation),
        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 fixture
            </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="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>
                                )}
                            />


                        </div>

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

}