import { useEffect, useState } from "react"
import { useForm, type ControllerProps, type FieldPath } from "react-hook-form"
import { Label } from "@/components/ui/label"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
    FormDescription,
} from "@/components/ui/form"
import { useCreateBanner, useUpdateBanner, useBanner } from "@/features/site-management/hooks/useBanners"
import { ArrowLeft, Upload, X } from "lucide-react"
import { getMediaUrl } from "@/lib/utils"

const formSchema = z.object({
    title: z.string().optional(),
    sub_title: z.string().optional(),
    link: z.string().optional(),
    is_active: z.boolean(),
})

type BannerFormValues = z.infer<typeof formSchema>

interface BannerFormProps {
    bannerId?: string | null
    onClose: () => void
}

const BannerFormField = <TName extends FieldPath<BannerFormValues>>(
    props: ControllerProps<BannerFormValues, TName>
) => {
    return <FormField<BannerFormValues, TName> {...props} />
}

export const BannerForm = ({ bannerId, onClose }: BannerFormProps) => {
    const { data: banner, isLoading: isLoadingBanner } = useBanner(bannerId || "")
    const createBanner = useCreateBanner()
    const updateBanner = useUpdateBanner()

    const [imagePreview, setImagePreview] = useState<string | null>(null)
    const [imageKPreview, setImageKPreview] = useState<string | null>(null)
    const [imageFile, setImageFile] = useState<File | null>(null)
    const [imageKFile, setImageKFile] = useState<File | null>(null)

    const form = useForm<BannerFormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            title: "",
            sub_title: "",
            link: "",
            is_active: true,
        },
    })

    useEffect(() => {
        if (banner) {
            form.reset({
                title: banner.title || "",
                sub_title: banner.sub_title || "",
                link: banner.link || "",
                is_active: banner.is_active,
            })
            if (banner.image) setImagePreview(getMediaUrl(banner.image))
            if (banner.image_k) setImageKPreview(getMediaUrl(banner.image_k))
        }
    }, [banner, form])

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>, type: 'main' | 'small') => {
        const file = e.target.files?.[0]
        if (file) {
            const reader = new FileReader()
            reader.onloadend = () => {
                if (type === 'main') {
                    setImageFile(file)
                    setImagePreview(reader.result as string)
                } else {
                    setImageKFile(file)
                    setImageKPreview(reader.result as string)
                }
            }
            reader.readAsDataURL(file)
        }
    }

    const onSubmit = (values: BannerFormValues) => {
        const formData = new FormData()

        if (values.title) formData.append("title", values.title)
        if (values.sub_title) formData.append("sub_title", values.sub_title)
        if (values.link) formData.append("link", values.link)
        formData.append("is_active", String(values.is_active))

        if (imageFile) formData.append("image", imageFile)
        if (imageKFile) formData.append("image_k", imageKFile)

        if (bannerId) {
            updateBanner.mutate(
                { id: bannerId, data: formData },
                { onSuccess: onClose }
            )
        } else {
            if (!imageFile) {
                form.setError("root", { message: "Ana görsel zorunludur" })
                return
            }
            createBanner.mutate(formData, { onSuccess: onClose })
        }
    }

    if (bannerId && isLoadingBanner) return <div>Yükleniyor...</div>

    return (
        <div className="space-y-6">
            <div className="flex items-center gap-4">
                <Button variant="ghost" size="icon" onClick={onClose}>
                    <ArrowLeft className="h-4 w-4" />
                </Button>
                <h2 className="text-2xl font-bold tracking-tight">
                    {bannerId ? "Banner Düzenle" : "Yeni Banner Ekle"}
                </h2>
            </div>

            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 max-w-2xl">
                    <div className="grid grid-cols-1 gap-6">
                        {/* Main Image Upload */}
                        <div className="space-y-2">
                            <Label className="flex w-full">
                                Ana Görsel <span className="text-red-500 ml-1">*</span>
                            </Label>
                            <div className="flex flex-col gap-4">
                                {imagePreview && (
                                    <div className="relative w-full aspect-video bg-gray-100 rounded-lg overflow-hidden border">
                                        <img src={imagePreview} alt="Preview" className="w-full h-full object-cover" />
                                        <Button
                                            type="button"
                                            variant="destructive"
                                            size="icon"
                                            className="absolute top-2 right-2 h-6 w-6"
                                            onClick={() => {
                                                setImageFile(null)
                                                setImagePreview(null)
                                            }}
                                        >
                                            <X className="h-4 w-4" />
                                        </Button>
                                    </div>
                                )}
                                <div className="flex items-center gap-2">
                                    <Input
                                        type="file"
                                        accept="image/*"
                                        onChange={(e) => handleFileChange(e, 'main')}
                                        className="hidden"
                                        id="main-image-upload"
                                    />
                                    <Button type="button" variant="outline" onClick={() => document.getElementById('main-image-upload')?.click()}>
                                        <Upload className="mr-2 h-4 w-4" />
                                        {imagePreview ? "Görseli Değiştir" : "Görsel Yükle"}
                                    </Button>
                                </div>
                                {form.formState.errors.root && (
                                    <p className="text-sm font-medium text-destructive">{form.formState.errors.root.message}</p>
                                )}
                            </div>
                        </div>

                        {/* Small Image Upload */}
                        <div className="space-y-2">
                            <Label>Küçük Görsel (Opsiyonel)</Label>
                            <div className="flex flex-col gap-4">
                                {imageKPreview && (
                                    <div className="relative w-32 h-32 bg-gray-100 rounded-lg overflow-hidden border">
                                        <img src={imageKPreview} alt="Preview Small" className="w-full h-full object-cover" />
                                        <Button
                                            type="button"
                                            variant="destructive"
                                            size="icon"
                                            className="absolute top-2 right-2 h-6 w-6"
                                            onClick={() => {
                                                setImageKFile(null)
                                                setImageKPreview(null)
                                            }}
                                        >
                                            <X className="h-4 w-4" />
                                        </Button>
                                    </div>
                                )}
                                <div className="flex items-center gap-2">
                                    <Input
                                        type="file"
                                        accept="image/*"
                                        onChange={(e) => handleFileChange(e, 'small')}
                                        className="hidden"
                                        id="small-image-upload"
                                    />
                                    <Button type="button" variant="outline" onClick={() => document.getElementById('small-image-upload')?.click()}>
                                        <Upload className="mr-2 h-4 w-4" />
                                        {imageKPreview ? "Görseli Değiştir" : "Görsel Yükle"}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <BannerFormField
                        control={form.control}
                        name="title"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Başlık</FormLabel>
                                <FormControl>
                                    <Input placeholder="Banner başlığı..." {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <BannerFormField
                        control={form.control}
                        name="sub_title"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Alt Başlık</FormLabel>
                                <FormControl>
                                    <Input placeholder="Alt açıklama..." {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <BannerFormField
                        control={form.control}
                        name="link"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Yönlendirme Linki</FormLabel>
                                <FormControl>
                                    <Input placeholder="https://..." {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <BannerFormField
                        control={form.control}
                        name="is_active"
                        render={({ field }) => (
                            <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                                <div className="space-y-0.5">
                                    <FormLabel className="text-base">Aktif Durum</FormLabel>
                                    <FormDescription>
                                        Bu banner sitede görüntülensin mi?
                                    </FormDescription>
                                </div>
                                <FormControl>
                                    <Switch
                                        checked={field.value}
                                        onCheckedChange={field.onChange}
                                    />
                                </FormControl>
                            </FormItem>
                        )}
                    />

                    <div className="flex justify-end gap-4">
                        <Button type="button" variant="outline" onClick={onClose}>İptal</Button>
                        <Button type="submit" disabled={createBanner.isPending || updateBanner.isPending}>
                            {bannerId ? "Güncelle" : "Kaydet"}
                        </Button>
                    </div>
                </form>
            </Form>
        </div>
    )
}
