import { useForm } from "react-hook-form"
import { getMediaUrl } from "@/lib/utils"
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 { Textarea } from "@/components/ui/textarea"
import { useCreateHome, useUpdateHome } from "../hooks/useHomes"
import { useTags } from "@/features/tags/hooks/useTags"
import type { Home, Tag } from "@/types/api"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"

// Schema needs to be loose for file input or we handle it manually
const homeSchema = z.object({
    name: z.string().min(1, "İsim zorunludur."),
    title: z.string().min(1, "Başlık zorunludur."),
    button1: z.string().optional(),
    button2: z.string().optional(),
    // Image is now a file list or string (if existing url)
    // We'll treat it as any for now to handle FileList from input and string from existing data
    image: z.any().optional(),
    video: z.string().optional(),
    keywords: z.string().optional(),
    is_active: z.boolean().default(true),
    tag_ids: z.array(z.string()).optional(),
})

type HomeFormValues = z.infer<typeof homeSchema>

interface HomeFormProps {
    home?: Home
    onSuccess: () => void
}

export function HomeForm({ home, onSuccess }: HomeFormProps) {
    const createMutation = useCreateHome()
    const updateMutation = useUpdateHome()
    const isEdit = !!home

    // Tag Selection Data
    const { data: tagsData } = useTags(1, 100)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const allTags: Tag[] = Array.isArray(tagsData) ? tagsData : (tagsData as any)?.data || (tagsData as any)?.tags || []

    const form = useForm<HomeFormValues>({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        resolver: zodResolver(homeSchema) as any,
        defaultValues: {
            name: home?.name || "",
            title: home?.title || "",
            button1: home?.button1 || "",
            button2: home?.button2 || "",
            image: home?.image || "",
            video: home?.video || "",
            keywords: home?.keywords || "",
            is_active: home?.is_active ?? true,
            tag_ids: home?.tags?.map(t => t.id) || [],
        },
    })

    useEffect(() => {
        if (home) {
            form.reset({
                name: home.name,
                title: home.title,
                button1: home.button1 || "",
                button2: home.button2 || "",
                image: home.image || "",
                video: home.video || "",
                keywords: home.keywords || "",
                is_active: home.is_active,
                tag_ids: home.tags?.map(t => t.id) || [],
            })
        } else {
            form.reset({
                name: "",
                title: "",
                button1: "",
                button2: "",
                image: "",
                video: "",
                keywords: "",
                is_active: true,
                tag_ids: [],
            })
        }
    }, [home, form])

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function onSubmit(data: any) {
        const formData = new FormData()
        formData.append('name', data.name)
        formData.append('title', data.title)
        if (data.button1) formData.append('button1', data.button1)
        if (data.button2) formData.append('button2', data.button2)
        if (data.video) formData.append('video', data.video)
        if (data.keywords) formData.append('keywords', data.keywords)
        formData.append('is_active', String(data.is_active))

        // Handle Image
        // If it's a FileList (from input), take the first file
        if (data.image instanceof FileList && data.image.length > 0) {
            formData.append('image', data.image[0])
        } else if (data.image instanceof File) {
            formData.append('image', data.image)
        }
        // If it's a string (existing URL), we might not need to send it if backend handles partial updates,
        // OR we don't append 'image' key so backend keeps existing.
        // If user didn't change image, data.image will be the string URL.

        // Handle Tags
        // Backend expects multiple 'tag_ids' keys: tag_ids=ID1&tag_ids=ID2...
        if (data.tag_ids && Array.isArray(data.tag_ids)) {
            data.tag_ids.forEach((id: string) => {
                formData.append('tag_ids', id)
            })
        }

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

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        control={form.control as any}
                        name="name"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>İsim (Slug)</FormLabel>
                                <FormControl>
                                    <Input placeholder="referans-adi" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <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="Görünen başlık" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        control={form.control as any}
                        name="button1"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Buton 1 Metni</FormLabel>
                                <FormControl>
                                    <Input placeholder="Daha Fazla" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        control={form.control as any}
                        name="button2"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Buton 2 Metni</FormLabel>
                                <FormControl>
                                    <Input placeholder="İletişime Geç" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <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 Yükle</FormLabel>
                            <FormControl>
                                <Input
                                    {...fieldProps}
                                    type="file"
                                    accept="image/*"
                                    onChange={(event) => {
                                        onChange(event.target.files && event.target.files[0])
                                    }}
                                />
                            </FormControl>
                            <FormDescription>
                                {value && typeof value === 'string' ? (
                                    <div className="mt-2">
                                        <p className="text-sm text-muted-foreground mb-1">Mevcut Resim:</p>
                                        <img src={getMediaUrl(value)} alt="Preview" className="h-20 w-auto object-cover rounded border" />
                                    </div>
                                ) : ''}
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="video"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Video URL</FormLabel>
                            <FormControl>
                                <Input placeholder="https://..." {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="keywords"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Anahtar Kelimeler</FormLabel>
                            <FormControl>
                                <Textarea placeholder="seo, keyword, listesi" className="resize-none" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    control={form.control as any}
                    name="tag_ids"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Etiketler</FormLabel>
                            <div className="grid grid-cols-2 gap-2 border p-3 rounded-md max-h-40 overflow-y-auto">
                                {allTags.map((tag) => (
                                    <FormItem key={tag.id} className="flex flex-row items-center space-x-2 space-y-0">
                                        <FormControl>
                                            <Checkbox
                                                checked={field.value?.includes(tag.id)}
                                                onCheckedChange={(checked) => {
                                                    return checked
                                                        ? field.onChange([...(field.value || []), tag.id])
                                                        : field.onChange(
                                                            field.value?.filter((value: string) => value !== tag.id)
                                                        )
                                                }}
                                            />
                                        </FormControl>
                                        <FormLabel className="font-normal cursor-pointer">
                                            {tag.tag}
                                        </FormLabel>
                                    </FormItem>
                                ))}
                                {allTags.length === 0 && <p className="text-sm text-muted-foreground">Etiket bulunamadı.</p>}
                            </div>
                            <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 içerik yayında olsun mu?
                                </FormDescription>
                            </div>
                        </FormItem>
                    )}
                />
                <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
                    {isEdit ? "Güncelle" : "Oluştur"}
                </Button>
            </form>
        </Form>
    )
}
