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 { Textarea } from "@/components/ui/textarea"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { useCreateSiteInfo, useUpdateSiteInfo, useSiteInfo } from "@/features/site-management/hooks/useSiteInfo"
import type { SiteInfo } from "@/types/api"
import { ArrowLeft, Upload, X } from "lucide-react"
import { getMediaUrl } from "@/lib/utils"

const formSchema = z.object({
    title: z.string().min(1, "Site başlığı zorunludur"),
    email: z.string().min(1, "Email zorunludur").email("Geçerli bir email giriniz"),
    phone: z.string().min(1, "Telefon numarası zorunludur"),
    address: z.string().optional(),
    copyright: z.string().optional(),
    map_embed: z.string().optional(),
})

type SiteInfoFormValues = z.infer<typeof formSchema>

interface SiteInfoFormProps {
    siteInfoId?: string | null
    onClose: () => void
}

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

export const SiteInfoForm = ({ siteInfoId, onClose }: SiteInfoFormProps) => {
    // Note: useSiteInfos returns an array, but if we are editing specific ID, we might use useSiteInfo logic.
    // However, the original code used useSiteInfos()[0].
    // If siteInfoId is provided, we should probably fetch that specific one or just use the single active one policy.
    // The previous code had: useSiteInfo(siteInfoId || "")
    // Let's assume useSiteInfo exists and is correct for fetching by ID.
    const { data: siteInfoData, isLoading } = useSiteInfo(siteInfoId || "")
    const siteInfo = siteInfoData as SiteInfo | undefined
    const createSiteInfo = useCreateSiteInfo()
    const updateSiteInfo = useUpdateSiteInfo()

    const [wLogoPreview, setWLogoPreview] = useState<string | null>(null)
    const [bLogoPreview, setBLogoPreview] = useState<string | null>(null)
    const [wLogoFile, setWLogoFile] = useState<File | null>(null)
    const [bLogoFile, setBLogoFile] = useState<File | null>(null)

    const form = useForm<SiteInfoFormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            title: "",
            email: "",
            phone: "",
            address: "",
            copyright: "",
            map_embed: "",
        },
    })

    useEffect(() => {
        if (siteInfo) {
            form.reset({
                title: siteInfo.title || "",
                email: siteInfo.email || "",
                phone: siteInfo.phone || "",
                address: siteInfo.address || "",
                copyright: siteInfo.copyright || "",
                map_embed: siteInfo.map_embed || "",
            })
            if (siteInfo.w_logo) setWLogoPreview(getMediaUrl(siteInfo.w_logo))
            if (siteInfo.b_logo) setBLogoPreview(getMediaUrl(siteInfo.b_logo))
        }
    }, [siteInfo, form])

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>, type: 'w_logo' | 'b_logo') => {
        const file = e.target.files?.[0]
        if (file) {
            const reader = new FileReader()
            reader.onloadend = () => {
                if (type === 'w_logo') {
                    setWLogoFile(file)
                    setWLogoPreview(reader.result as string)
                } else {
                    setBLogoFile(file)
                    setBLogoPreview(reader.result as string)
                }
            }
            reader.readAsDataURL(file)
        }
    }

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

        if (values.title) formData.append("title", values.title)
        if (values.email) formData.append("email", values.email)
        if (values.phone) formData.append("phone", values.phone)
        if (values.address) formData.append("address", values.address)
        if (values.copyright) formData.append("copyright", values.copyright)
        if (values.map_embed) formData.append("map_embed", values.map_embed)

        if (wLogoFile) formData.append("w_logo", wLogoFile)
        if (bLogoFile) formData.append("b_logo", bLogoFile)

        if (siteInfoId) {
            updateSiteInfo.mutate({ id: siteInfoId, data: formData }, { onSuccess: onClose })
        } else {
            createSiteInfo.mutate(formData, { onSuccess: onClose })
        }
    }

    if (siteInfoId && isLoading) 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">
                    {siteInfoId ? "Site Bilgilerini Düzenle" : "Yeni Site Bilgisi Ekle"}
                </h2>
            </div>

            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8 max-w-2xl">

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {/* White Logo Upload */}
                        <div className="space-y-2">
                            <Label>Beyaz Logo (Dark Mode)</Label>
                            <div className="flex flex-col gap-4">
                                {wLogoPreview && (
                                    <div className="relative w-full h-32 bg-gray-900 rounded-lg overflow-hidden border flex items-center justify-center">
                                        <img src={wLogoPreview} alt="White Logo" className="max-h-full max-w-full object-contain" />
                                        <Button
                                            type="button"
                                            variant="destructive"
                                            size="icon"
                                            className="absolute top-2 right-2 h-6 w-6"
                                            onClick={() => {
                                                setWLogoFile(null)
                                                setWLogoPreview(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, 'w_logo')}
                                        className="hidden"
                                        id="w-logo-upload"
                                    />
                                    <Button type="button" variant="outline" onClick={() => document.getElementById('w-logo-upload')?.click()}>
                                        <Upload className="mr-2 h-4 w-4" />
                                        {wLogoPreview ? "Logoyu Değiştir" : "Logo Yükle"}
                                    </Button>
                                </div>
                            </div>
                        </div>

                        {/* Black Logo Upload */}
                        <div className="space-y-2">
                            <Label>Siyah Logo (Light Mode)</Label>
                            <div className="flex flex-col gap-4">
                                {bLogoPreview && (
                                    <div className="relative w-full h-32 bg-gray-100 rounded-lg overflow-hidden border flex items-center justify-center">
                                        <img src={bLogoPreview} alt="Black Logo" className="max-h-full max-w-full object-contain" />
                                        <Button
                                            type="button"
                                            variant="destructive"
                                            size="icon"
                                            className="absolute top-2 right-2 h-6 w-6"
                                            onClick={() => {
                                                setBLogoFile(null)
                                                setBLogoPreview(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, 'b_logo')}
                                        className="hidden"
                                        id="b-logo-upload"
                                    />
                                    <Button type="button" variant="outline" onClick={() => document.getElementById('b-logo-upload')?.click()}>
                                        <Upload className="mr-2 h-4 w-4" />
                                        {bLogoPreview ? "Logoyu Değiştir" : "Logo Yükle"}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    </div>


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

                    <SiteInfoFormField
                        control={form.control}
                        name="email"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Email Adresi</FormLabel>
                                <FormControl>
                                    <Input placeholder="iletisim@example.com" {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <SiteInfoFormField
                        control={form.control}
                        name="phone"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Telefon Numarası</FormLabel>
                                <FormControl>
                                    <Input placeholder="+90 555 123 45 67" {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <SiteInfoFormField
                        control={form.control}
                        name="address"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Adres</FormLabel>
                                <FormControl>
                                    <Textarea placeholder="Şirket adresi..." className="min-h-[100px]" {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <SiteInfoFormField
                        control={form.control}
                        name="copyright"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Copyright Metni</FormLabel>
                                <FormControl>
                                    <Input placeholder="© 2024 Tüm hakları saklıdır." {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <SiteInfoFormField
                        control={form.control}
                        name="map_embed"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Google Maps Embed Kodu</FormLabel>
                                <FormControl>
                                    <Textarea placeholder='<iframe src="..." ...></iframe>' className="min-h-[100px] font-mono text-sm" {...field} value={field.value || ""} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

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