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 { useCreateServiceTitle, useUpdateServiceTitle } from "../hooks/useServiceTitles"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"
import type { ServiceTitle } from "@/types/api"

const serviceTitleSchema = z.object({
    title: z.string().min(1, "Başlık zorunludur."),
    title_sub: z.string().min(1, "Alt başlık zorunludur."),
    is_active: z.boolean().default(true),
})

type ServiceTitleFormValues = z.infer<typeof serviceTitleSchema>

interface ServiceTitleFormProps {
    serviceTitle?: ServiceTitle
    onSuccess: () => void
}

export function ServiceTitleForm({ serviceTitle, onSuccess }: ServiceTitleFormProps) {
    const createMutation = useCreateServiceTitle()
    const updateMutation = useUpdateServiceTitle()
    const isEdit = !!serviceTitle

    const form = useForm<ServiceTitleFormValues>({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        resolver: zodResolver(serviceTitleSchema) as any,
        defaultValues: {
            title: serviceTitle?.title || "",
            title_sub: serviceTitle?.title_sub || "",
            is_active: serviceTitle?.is_active ?? true,
        },
    })

    useEffect(() => {
        if (serviceTitle) {
            form.reset({
                title: serviceTitle.title,
                title_sub: serviceTitle.title_sub,
                is_active: serviceTitle.is_active,
            })
        } else {
            form.reset({
                title: "",
                title_sub: "",
                is_active: true,
            })
        }
    }, [serviceTitle, form])

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function onSubmit(data: any) {
        if (isEdit) {
            updateMutation.mutate({ id: serviceTitle!.id, data }, {
                onSuccess: () => {
                    showToast("Başlık başarıyla güncellendi.", "success")
                    onSuccess()
                },
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                onError: (error: any) => {
                    showToast(error.response?.data?.message || "Güncelleme hatası.", "error")
                }
            })
        } else {
            createMutation.mutate(data, {
                onSuccess: () => {
                    showToast("Başlık başarıyla oluşturuldu.", "success")
                    onSuccess()
                },
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                onError: (error: any) => {
                    showToast(error.response?.data?.message || "Oluşturma hatası.", "error")
                }
            })
        }
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="title"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Başlık</FormLabel>
                            <FormControl><Input placeholder="Örn: Servisler" {...field} /></FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="title_sub"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Alt Başlık</FormLabel>
                            <FormControl><Input placeholder="Örn: Neler Yapıyorum" {...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} onCheckedChange={field.onChange} />
                            </FormControl>
                            <div className="space-y-1 leading-none">
                                <FormLabel>Aktif</FormLabel>
                                <FormDescription>Bu başlık sitede kullanılsın mı?</FormDescription>
                            </div>
                        </FormItem>
                    )}
                />

                <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending} className="w-full">
                    {createMutation.isPending || updateMutation.isPending ? "Kaydediliyor..." : (isEdit ? "Güncelle" : "Oluştur")}
                </Button>
            </form>
        </Form>
    )
}
