"use client";

import { toast } from "sonner";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import CKEditorDynamic from "@/components/ckeditor-dynamic";

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 { geOneNews, updateNews } from "@/lib/features/admin/news/service";
import { NewsFormValidation } from "@/lib/features/admin/news/schema";
import { ResponseProps } from "@/lib/features/login/type";
import Loading from "../../components/loading";
import { ErrorMessage } from "@/components/ui/error-message";


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

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

    // states
    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

    const [subTitle, setSubTitle] = useState('');
    const [image, setImage] = useState('');

    const [status, setStatus] = useState('1');
    const [sending, setSending] = useState(false);


    const queryClient = useQueryClient();

    const mutation = useMutation({
        mutationFn: updateNews,
        onSuccess: (data) => {
            queryClient.invalidateQueries({ queryKey: ["updateNews"] });
            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);
            }
        },
        onError: (error) => {
            const newError = error as unknown as ErrorResponseProps;
            toast.error(newError?.response?.data?.message);
            return false;
        },
    });

    function onSubmit() {

        if (title === null || title === '') {
            toast.error("Title is required");
            return false;
        }

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

        else if (subTitle === null || subTitle === '') {
            toast.error("Sub title is required");
            return false;
        }

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

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

        else {

            setSending(true);

            const body = {
                title: title,
                subTitle: subTitle,
                desc: desc,
                image: image,
                status: status,
                newsId: dataId
            }

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

            mutation.mutate(body);
        }
    }


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


    // Update states
    useEffect(() => {
        if (data?.data?.details) {
            setTitle(data?.data?.details?.title)
            setSubTitle(data?.data?.details?.subtitle)

            setDesc(data?.data?.details?.description);
            setImage(data?.data?.details?.image)

        }

    }, [data]);


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

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

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


    return (
        <div className="h-auto max-h-[80vh] overflow-y-auto scrollbar-hide">
            <div className="text-sm font-medium text-center text-neutral-600 pb-4">
                Update news
            </div>

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

                        <div className="grid grid-cols-1 gap-2">

                            <div className="grid grid-cols-2 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="subTitle"
                                    render={({ }) => (
                                        <FormItem>
                                            <FormLabel>Sub Title</FormLabel>
                                            <FormControl>
                                                <Input type="text" value={subTitle} onChange={(e) => setSubTitle(e.target.value)} />
                                            </FormControl>
                                            <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="image"
                                    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>

                            <FormField
                                control={form.control}
                                name="desc"
                                render={({ }) => (
                                    <FormItem>
                                        <FormLabel>Description</FormLabel>
                                        <FormControl>
                                            <div className="border border-input rounded-md overflow-y-auto max-h-96">
                                                <CKEditorDynamic
                                                    data={desc}
                                                    onChange={(data) => setDesc(data)}
                                                />
                                            </div>
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                        </div>

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


};