import { useEffect } from "react"
import { useForm, type ControllerProps, type FieldPath } from "react-hook-form"
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 { useCreateMainMenu, useUpdateMainMenu, useMainMenu } from "@/features/main-menu/hooks/useMainMenu"
import { ArrowLeft, Save } from "lucide-react"

const formSchema = z.object({
    home: z.string().min(1, "Anasayfa başlığı zorunludur"),
    about: z.string().min(1, "Hakkımda başlığı zorunludur"),
    services: z.string().min(1, "Hizmetler başlığı zorunludur"),
    resume: z.string().min(1, "Özgeçmiş başlığı zorunludur"),
    portfolio: z.string().min(1, "Portfolyo başlığı zorunludur"),
    contact: z.string().min(1, "İletişim başlığı zorunludur"),
    is_active: z.boolean(),
})

type MainMenuFormValues = z.infer<typeof formSchema>

interface MainMenuFormProps {
    menuId?: string | null
    onClose: () => void
}

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

export const MainMenuForm = ({ menuId, onClose }: MainMenuFormProps) => {
    const { data: menu, isLoading: isLoadingMenu } = useMainMenu(menuId || "")
    const createMenu = useCreateMainMenu()
    const updateMenu = useUpdateMainMenu()

    const form = useForm<MainMenuFormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            home: "Home",
            about: "About",
            services: "Services",
            resume: "Resume",
            portfolio: "Portfolio",
            contact: "Contact",
            is_active: true,
        },
    })

    useEffect(() => {
        if (menu) {
            form.reset({
                home: menu.home,
                about: menu.about,
                services: menu.services,
                resume: menu.resume,
                portfolio: menu.portfolio,
                contact: menu.contact,
                is_active: menu.is_active,
            })
        }
    }, [menu, form])

    const onSubmit = (values: MainMenuFormValues) => {
        if (menuId) {
            updateMenu.mutate(
                { id: menuId, data: values },
                { onSuccess: onClose }
            )
        } else {
            createMenu.mutate(values, { onSuccess: onClose })
        }
    }

    if (menuId && isLoadingMenu) 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">
                    {menuId ? "Menü Düzenle" : "Yeni Menü 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">
                        <MainMenuFormField
                            control={form.control}
                            name="home"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Anasayfa Başlığı</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Home" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <MainMenuFormField
                            control={form.control}
                            name="about"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Hakkımda Başlığı</FormLabel>
                                    <FormControl>
                                        <Input placeholder="About" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <MainMenuFormField
                            control={form.control}
                            name="services"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Hizmetler Başlığı</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Services" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <MainMenuFormField
                            control={form.control}
                            name="resume"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Özgeçmiş Başlığı</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Resume" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <MainMenuFormField
                            control={form.control}
                            name="portfolio"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Portfolyo Başlığı</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Portfolio" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <MainMenuFormField
                            control={form.control}
                            name="contact"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>İletişim Başlığı</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Contact" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>

                    <MainMenuFormField
                        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 menü yapılandırması sitede aktif olsun mu?
                                    </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={createMenu.isPending || updateMenu.isPending}>
                            <Save className="mr-2 h-4 w-4" />
                            {menuId ? "Güncelle" : "Kaydet"}
                        </Button>
                    </div>
                </form>
            </Form>
        </div>
    )
}
