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 { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { Separator } from "@/components/ui/separator"
import { useCreateAbout, useUpdateAbout } from "../hooks/useAbout"
import { useEffect } from "react"
import { showToast } from "@/lib/sweetalert"
import { getMediaUrl } from "@/lib/utils"
import type { About } from "@/types/api"

const aboutSchema = z.object({
    title: z.string().min(1, "Başlık zorunludur."),
    image_sub: z.string().optional(),
    birthday: z.string().optional(),
    city: z.string().optional(),
    study: z.string().optional(),
    website: z.string().optional(),
    phone: z.string().optional(),
    age: z.coerce.number().optional(),
    interests: z.string().optional(),
    degree: z.string().optional(),
    x: z.string().optional(),
    mail: z.string().email("Geçerli bir e-posta giriniz.").optional().or(z.literal("")),

    // Stats
    done: z.coerce.number().optional(),
    project_done: z.string().optional(),
    user_h: z.coerce.number().optional(),
    hapy_user: z.string().optional(),
    great: z.coerce.number().optional(),
    great_reviews: z.string().optional(),
    team: z.coerce.number().optional(),
    support_team: z.string().optional(),

    is_active: z.boolean().default(true),
    counter_active: z.boolean().default(true),

    // Files
    image: z.any().optional(),
    cv: z.any().optional(),
})

type AboutFormValues = z.infer<typeof aboutSchema>

interface AboutFormProps {
    about?: About
    onSuccess: () => void
}

export function AboutForm({ about, onSuccess }: AboutFormProps) {
    const createMutation = useCreateAbout()
    const updateMutation = useUpdateAbout()
    const isEdit = !!about

    const form = useForm<AboutFormValues>({
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        resolver: zodResolver(aboutSchema) as any,
        defaultValues: {
            title: about?.title || "",
            image_sub: about?.image_sub || "",
            birthday: about?.birthday?.split("T")[0] || "",
            city: about?.city || "",
            study: about?.study || "",
            website: about?.website || "",
            phone: about?.phone || "",
            age: about?.age || 0,
            interests: about?.interests || "",
            degree: about?.degree || "",
            x: about?.x || "",
            mail: about?.mail || "",
            done: about?.done || 0,
            project_done: about?.project_done || "",
            user_h: about?.user_h || 0,
            hapy_user: about?.hapy_user || "",
            great: about?.great || 0,
            great_reviews: about?.great_reviews || "",
            team: about?.team || 0,
            support_team: about?.support_team || "",
            is_active: about?.is_active ?? true,
            counter_active: about?.counter_active ?? true,
            image: undefined,
            cv: undefined,
        },
    })

    useEffect(() => {
        if (about) {
            form.reset({
                title: about.title,
                image_sub: about.image_sub || "",
                birthday: about.birthday?.split("T")[0] || "",
                city: about.city || "",
                study: about.study || "",
                website: about.website || "",
                phone: about.phone || "",
                age: about.age || 0,
                interests: about.interests || "",
                degree: about.degree || "",
                x: about.x || "",
                mail: about.mail || "",
                done: about.done || 0,
                project_done: about.project_done || "",
                user_h: about.user_h || 0,
                hapy_user: about.hapy_user || "",
                great: about.great || 0,
                great_reviews: about.great_reviews || "",
                team: about.team || 0,
                support_team: about.support_team || "",
                is_active: about.is_active,
                counter_active: about.counter_active,
            })
        } else {
            form.reset({
                title: "",
                image_sub: "",
                birthday: "",
                city: "",
                study: "",
                website: "",
                phone: "",
                age: 0,
                interests: "",
                degree: "",
                x: "",
                mail: "",
                done: 0,
                project_done: "",
                user_h: 0,
                hapy_user: "",
                great: 0,
                great_reviews: "",
                team: 0,
                support_team: "",
                is_active: true,
                counter_active: true,
            })
        }
    }, [about, form])

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    async function onSubmit(data: any) {
        // If "Active" is selected, we must deactivate all other records first
        if (data.is_active) {
            try {
                // Fetch all records (assuming less than 1000 for now)
                const response = await import("@/services/aboutService").then(m => m.aboutService.getAll(1, 1000))
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const allAbouts = Array.isArray(response) ? response : (response as any)?.data || []

                // Find other active records
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const otherActiveAbouts = allAbouts.filter((a: any) => a.is_active && a.id !== about?.id)

                if (otherActiveAbouts.length > 0) {
                    // Deactivate them sequentially to avoid race conditions or backend overload
                    const { aboutService } = await import("@/services/aboutService")
                    for (const other of otherActiveAbouts) {
                        // We send the full object but with is_active: false.
                        // The service converts this to fields. Strings remain strings. 
                        // Files (image/cv) are not re-sent if they are just URL strings, which usually means "keep existing".
                        await aboutService.update(other.id, { ...other, is_active: false })
                    }
                    showToast(`${otherActiveAbouts.length} diğer kayıt pasif yapıldı.`, "info")
                }
            } catch (error) {
                console.error("Error deactivating other records:", error)
                // We show a warning but permit the save to proceed
                showToast("Diğer kayıtlar pasif yapılırken hata oluştu.", "warning")
            }
        }

        if (isEdit) {
            updateMutation.mutate({ id: about!.id, data }, {
                onSuccess: () => {
                    showToast("Hakkımda bilgisi 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("Hakkımda bilgisi 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">

                {/* Genel Bilgiler */}
                <div className="space-y-4 rounded-md border p-4 bg-white dark:bg-gray-800 h-[400px] overflow-y-auto">
                    <h3 className="text-lg font-medium sticky top-0 bg-white dark:bg-gray-800 z-10 py-2">Genel Bilgiler</h3>
                    <Separator />
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <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="Hakkımda..." {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="image_sub"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Resim Altı Yazısı</FormLabel>
                                    <FormControl><Input placeholder="Örn: Developer & Designer" {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <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>Profil Resmi</FormLabel>
                                    <FormControl>
                                        <Input
                                            {...fieldProps}
                                            type="file"
                                            accept="image/*"
                                            onChange={(event) => {
                                                onChange(event.target.files && event.target.files[0])
                                            }}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        {about?.image && (
                                            <div className="mt-2 text-xs">
                                                Mevcut: <a href={getMediaUrl(about.image)} target="_blank" rel="noreferrer" className="text-blue-500 underline">Görüntüle</a>
                                                <img src={getMediaUrl(about.image)} alt="Preview" className="h-16 w-16 object-cover mt-1 rounded-full border" />
                                            </div>
                                        )}
                                    </FormDescription>
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="cv"
                            // eslint-disable-next-line @typescript-eslint/no-unused-vars
                            render={({ field: { value, onChange, ...fieldProps } }) => (
                                <FormItem>
                                    <FormLabel>CV (PDF)</FormLabel>
                                    <FormControl>
                                        <Input
                                            {...fieldProps}
                                            type="file"
                                            accept=".pdf,.doc,.docx"
                                            onChange={(event) => {
                                                onChange(event.target.files && event.target.files[0])
                                            }}
                                        />
                                    </FormControl>
                                    <FormDescription>
                                        {about?.cv && (
                                            <div className="mt-2 text-xs">
                                                Mevcut: <a href={getMediaUrl(about.cv)} target="_blank" rel="noreferrer" className="text-blue-500 underline">İndir/Görüntüle</a>
                                            </div>
                                        )}
                                    </FormDescription>
                                </FormItem>
                            )}
                        />
                    </div>

                    <h3 className="text-lg font-medium pt-4">Kişisel Detaylar</h3>
                    <Separator />
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="birthday"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Doğum Günü</FormLabel>
                                    <FormControl><Input type="date" {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="age"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Yaş</FormLabel>
                                    <FormControl><Input type="number" {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="city"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Şehir</FormLabel>
                                    <FormControl><Input placeholder="Istanbul" {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="degree"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Eğitim Derecesi</FormLabel>
                                    <FormControl><Input placeholder="Lisans" {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="study"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Okul/Bölüm</FormLabel>
                                    <FormControl><Input placeholder="Üniversite..." {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="mail"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>E-posta</FormLabel>
                                    <FormControl><Input type="email" placeholder="email@example.com" {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="phone"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Telefon</FormLabel>
                                    <FormControl><Input placeholder="555..." {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="website"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Web Sitesi</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="x"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>X (Twitter) Handle</FormLabel>
                                    <FormControl><Input placeholder="@handle" {...field} /></FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>
                    <FormField
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        control={form.control as any}
                        name="interests"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>İlgi Alanları</FormLabel>
                                <FormControl><Textarea placeholder="Go, React, Docker..." className="resize-none" {...field} /></FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <h3 className="text-lg font-medium pt-4">İstatistik Sayaçları</h3>
                    <Separator />
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                        <div className="space-y-2 border p-2 rounded">
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="done"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Tamamlanan (Sayı)</FormLabel>
                                        <FormControl><Input type="number" {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="project_done"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Etiket (Örn: Proje)</FormLabel>
                                        <FormControl><Input {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                        </div>

                        <div className="space-y-2 border p-2 rounded">
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="user_h"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Mutlu Kullanıcı (Sayı)</FormLabel>
                                        <FormControl><Input type="number" {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="hapy_user"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Etiket</FormLabel>
                                        <FormControl><Input {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                        </div>

                        <div className="space-y-2 border p-2 rounded">
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="great"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Yorumlar (Sayı)</FormLabel>
                                        <FormControl><Input type="number" {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="great_reviews"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Etiket</FormLabel>
                                        <FormControl><Input {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                        </div>

                        <div className="space-y-2 border p-2 rounded">
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="team"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Destek (Sayı)</FormLabel>
                                        <FormControl><Input type="number" {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                            <FormField
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                control={form.control as any}
                                name="support_team"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Etiket</FormLabel>
                                        <FormControl><Input {...field} /></FormControl>
                                    </FormItem>
                                )}
                            />
                        </div>
                    </div>

                    <h3 className="text-lg font-medium pt-4">Görünürlük Ayarları</h3>
                    <Separator />
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <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>Hakkımda alanı sitede görünsün mü?</FormDescription>
                                    </div>
                                </FormItem>
                            )}
                        />
                        <FormField
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
                            control={form.control as any}
                            name="counter_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>Sayaçlar Aktif</FormLabel>
                                        <FormDescription>İstatistik sayaçları sitede görünsün mü?</FormDescription>
                                    </div>
                                </FormItem>
                            )}
                        />
                    </div>
                </div>

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