import { useForm } from "react-hook-form"
import { Textarea } from "@/components/ui/textarea"

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 { useCreateService, useUpdateService } from "../hooks/useServices"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"
import { getMediaUrl } from "@/lib/utils"
import type { Service } from "@/types/api"

const serviceSchema = z.object({
    title: z.string().min(1, "Başlık zorunludur."),
    content: z.string().optional(),
    is_active: z.boolean().default(true),
    image: z.any().optional(),
    slug: z.string().optional(),
})

type ServiceFormValues = z.infer<typeof serviceSchema>

interface ServiceFormProps {
    service?: Service
    onSuccess: () => void
}

export function ServiceForm({ service, onSuccess }: ServiceFormProps) {
    const createMutation = useCreateService()
    const updateMutation = useUpdateService()
    const isEdit = !!service

    const form = useForm<ServiceFormValues>({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        resolver: zodResolver(serviceSchema) as any,
        defaultValues: {
            title: service?.title || "",
            content: service?.content || "",
            is_active: service?.is_active ?? true,
            slug: service?.slug || "",
            image: undefined,
        },
    })

    useEffect(() => {
        if (service) {
            form.reset({
                title: service.title,
                content: service.content || "",
                is_active: service.is_active,
                slug: service.slug,
            })
        } else {
            form.reset({
                title: "",
                content: "",
                is_active: true,
                slug: "",
            })
        }
    }, [service, form])

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function onSubmit(data: any) {
        if (isEdit) {
            updateMutation.mutate({ id: service!.id, data }, {
                onSuccess: () => {
                    showToast("Hizmet 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("Hizmet 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="Hizmet Başlığı" {...field} /></FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="content"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>İçerik (HTML)</FormLabel>
                            <FormControl>
                                <Textarea
                                    placeholder="<p>Hizmet içeriği...</p>"
                                    className="min-h-[150px]"
                                    {...field}
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="image"
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    render={({ field: { value, onChange, ...fieldProps } }) => (
                        <FormItem>
                            <FormLabel>Görsel</FormLabel>
                            <FormControl>
                                <Input
                                    {...fieldProps}
                                    type="file"
                                    accept="image/*"
                                    onChange={(event) => {
                                        onChange(event.target.files && event.target.files[0])
                                    }}
                                />
                            </FormControl>
                            <FormDescription>
                                {service?.image && (
                                    <span className="mt-2 text-xs block">
                                        Mevcut: <a href={getMediaUrl(service.image)} target="_blank" rel="noreferrer" className="text-blue-500 underline">Görüntüle</a>
                                        <img src={getMediaUrl(service.image)} alt="Preview" className="h-16 w-16 object-cover mt-1 rounded border" />
                                    </span>
                                )}
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                {isEdit && (
                    <FormField
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        control={form.control as any}
                        name="slug"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Slug (URL Yolu)</FormLabel>
                                <FormControl><Input placeholder="ornek-hizmet" {...field} /></FormControl>
                                <FormDescription>Boş bırakılırsa başlıktan otomatik oluşturulur.</FormDescription>
                                <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 hizmet sitede yayınlansı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>
    )
}
