"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 { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { LoaderCircle } from "lucide-react";
import { ResponseProps } from "@/lib/features/login/type";
import { VideoFormValidation } from "@/lib/features/admin/video/schema";
import { createVideo } from "@/lib/features/admin/video/service";

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

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

    // states
    const [title, setTitle] = useState('');
    const [category, setCategory] = useState('');

    const [image, setImage] = useState('');
    const [video, setVideo] = useState('');

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



    const queryClient = useQueryClient();

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

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

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

        else if (image === null || image === '') {
            toast.error("Image url is required");
            return false;
        }

        else if (video === null || video === '') {
            toast.error("Video link is required");
            return false;
        }

        else {

            setSending(true);

            const body = {
                title: title,
                category: category,
                image: image,
                video: video
            }

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

            mutation.mutate(body);
        }
    }



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


    return (
        <div>
            <div className="text-sm font-medium text-center text-neutral-600 pb-4">
                Create new video
            </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="title"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Title</FormLabel>
                                        <FormControl>
                                            <Input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

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

                                            <option key="HIGHLIGHT" value="HIGHLIGHT">HIGHLIGHT</option>
                                            <option key="SKILLS" value="SKILLS">SKILLS</option>

                                            <option key="INTERVIEW" value="INTERVIEW">INTERVIEW</option>


                                        </select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

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


                        </div>

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

}