import {Button} from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";
import {Input} from "@/components/ui/input";
import {Label} from "@/components/ui/label";
import {Settings} from "./SettingsPage";
import {toast} from "sonner";
import {useState} from "react";
import {useForm} from "react-hook-form";
import {z} from "zod";
import {zodResolver} from "@hookform/resolvers/zod";
import {useQuery} from "@tanstack/react-query";
import {getSettings} from "@/utils/querys/settings";
import {useSessionStore} from "@/lib/store/sessionStore";
import axios from "axios";

const FormSchema = z.object({
    value: z.string().min(1, "You must enter a value greater than 0"),
});
export function ChangeSetting({setting}: {setting: Settings}) {
    const {token} = useSessionStore();
    const {refetch} = useQuery(getSettings(token ?? ""));

    const [open, setOpen] = useState(false);
    const [saving, setSaving] = useState(false);
    const {
        register,
        handleSubmit,
        reset,
        formState: {errors},
    } = useForm<z.infer<typeof FormSchema>>({
        resolver: zodResolver(FormSchema),
        defaultValues: {
            value: setting.value || "",
        },
    });

    const onSubmit = async (data: z.infer<typeof FormSchema>) => {
        setSaving(!saving);
        const update = {...data, name: setting.name};
        // console.log(update);
        try {
            const result = await axios.patch("/api/server/settings", update, {
                headers: {Authorization: `Bearer ${token}`},
            });

            if (result.data.success) {
                setOpen(!open);
                setSaving(false);
                refetch();
                toast.success(result.data.message);
            }
        } catch (error) {
            console.log(error);
        }
    };
    return (
        <>
            <Dialog
                open={open}
                onOpenChange={(isOpen) => {
                    if (!open) {
                        reset();
                    }
                    setOpen(isOpen);
                    // toast.message("Model was something", {
                    //     description: isOpen ? "Modal is open" : "Modal is closed",
                    // });
                }}
            >
                <DialogTrigger asChild>
                    <Button variant="outline">Edit</Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-[425px]">
                    <DialogHeader>
                        <DialogTitle>{setting.name}</DialogTitle>
                        <DialogDescription>
                            Update the setting and press save to complete the changes.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <div>
                            <>
                                <Label htmlFor={"value"} className="m-1">
                                    Value
                                </Label>
                                <Input
                                    {...register("value")}
                                    className={errors.value ? "border-red-500" : ""}
                                    aria-invalid={!!errors.value}
                                />
                                {errors.value && <p className="text-red-500 text-sm mt-1">{errors.value.message}</p>}
                            </>
                        </div>

                        <DialogFooter>
                            <div className="flex justify-end mt-2">
                                <Button type="submit" disabled={saving}>
                                    {saving ? (
                                        <>
                                            <span>Saving....</span>
                                        </>
                                    ) : (
                                        <span>Save setting</span>
                                    )}
                                </Button>
                            </div>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </>
    );
}
