import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Checkbox } from "@/components/ui/checkbox"
import { useCreateTag, useUpdateTag } from "../hooks/useTags"
import type { Tag } from "@/types/api"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"

const tagSchema = z.object({
    tag: z.string().min(1, "Etiket adı zorunludur."),
    is_active: z.boolean().default(true),
})

type TagFormValues = z.infer<typeof tagSchema>

interface TagFormProps {
    tag?: Tag
    onSuccess: () => void
}

export function TagForm({ tag: initialTag, onSuccess }: TagFormProps) {
    const createMutation = useCreateTag()
    const updateMutation = useUpdateTag()
    const isEdit = !!initialTag

    const form = useForm<TagFormValues>({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        resolver: zodResolver(tagSchema) as any,
        defaultValues: {
            tag: initialTag?.tag || "",
            is_active: initialTag?.is_active ?? true,
        },
    })

    useEffect(() => {
        if (initialTag) {
            form.reset({
                tag: initialTag.tag,
                is_active: initialTag.is_active,
            })
        } else {
            form.reset({
                tag: "",
                is_active: true,
            })
        }
    }, [initialTag, form])

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function onSubmit(data: any) {
        if (isEdit) {
            updateMutation.mutate({ id: initialTag!.id, data }, {
                onSuccess: () => {
                    showToast("Etiket başarıyla güncellendi.", "success")
                    onSuccess()
                },
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                onError: (error: any) => {
                    showToast(error.response?.data?.message || "Etiket güncellenirken hata oluştu.", "error")
                }
            })
        } else {
            createMutation.mutate(data, {
                onSuccess: () => {
                    showToast("Etiket başarıyla oluşturuldu.", "success")
                    onSuccess()
                },
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                onError: (error: any) => {
                    showToast(error.response?.data?.message || "Etiket oluşturulurken hata oluştu.", "error")
                }
            })
        }
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="tag"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Etiket Adı</FormLabel>
                            <FormControl>
                                <Input placeholder="Örn: VIP" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="is_active"
                    render={({ field }) => (
                        <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                            <FormControl>
                                <Checkbox
                                    checked={field.value as boolean}
                                    onCheckedChange={field.onChange}
                                />
                            </FormControl>
                            <div className="space-y-1 leading-none">
                                <FormLabel>
                                    Aktif
                                </FormLabel>
                                <FormDescription>
                                    Bu etiket kullanılabilir mi?
                                </FormDescription>
                            </div>
                        </FormItem>
                    )}
                />
                <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
                    {isEdit ? "Güncelle" : "Oluştur"}
                </Button>
            </form>
        </Form>
    )
}
