import { useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
    FormDescription,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { useCreateResume, useUpdateResume, useResume } from "@/features/resume/hooks/useResumes"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { EducationList } from "./EducationList"
import { ExperienceList } from "./ExperienceList"
import { SkillList } from "./SkillList"
import { KnowledgeList } from "./KnowledgeList"

const formSchema = z.object({
    title: z.string().min(2, "Başlık en az 2 karakter olmalıdır"),
    title_sub: z.string().min(2, "Alt başlık en az 2 karakter olmalıdır"),
    education: z.string().min(2, "Eğitim başlığı en az 2 karakter olmalıdır"),
    experience: z.string().min(2, "Deneyim başlığı en az 2 karakter olmalıdır"),
    coding_skills: z.string().min(2, "Yazılım yetenekleri başlığı en az 2 karakter olmalıdır"),
    knowledge: z.string().min(2, "Bilgi başlığı en az 2 karakter olmalıdır"),
    is_active: z.boolean(),
})

interface ResumeFormProps {
    isOpen: boolean
    onClose: () => void
    resumeId: string | null
}

export const ResumeForm = ({ isOpen, onClose, resumeId }: ResumeFormProps) => {
    const { data: resume, isLoading: isResumeLoading } = useResume(resumeId || "")
    const createResume = useCreateResume()
    const updateResume = useUpdateResume()

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            title: "",
            title_sub: "",
            education: "Education",
            experience: "Experience",
            coding_skills: "Coding Skills",
            knowledge: "Knowledge",
            is_active: false,
        },
    })

    useEffect(() => {
        if (resume) {
            form.reset({
                title: resume.title,
                title_sub: resume.title_sub,
                education: resume.education,
                experience: resume.experience,
                coding_skills: resume.coding_skills,
                knowledge: resume.knowledge,
                is_active: resume.is_active || false,
            })
        } else {
            form.reset({
                title: "",
                title_sub: "",
                education: "Education",
                experience: "Experience",
                coding_skills: "Coding Skills",
                knowledge: "Knowledge",
                is_active: false,
            })
        }
    }, [resume, form])

    const onSubmit = (values: z.infer<typeof formSchema>) => {
        if (resumeId) {
            updateResume.mutate(
                { id: resumeId, data: values },
                {
                    onSuccess: () => {
                        // Don't close immediately in edit mode to allow editing tabs
                        // onClose() 
                    },
                }
            )
        } else {
            createResume.mutate(values, {
                onSuccess: () => {
                    onClose()
                },
            })
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className={`${resumeId ? "sm:max-w-[800px]" : "sm:max-w-[600px]"} max-h-[90vh] overflow-y-auto`}>
                <DialogHeader>
                    <DialogTitle>{resumeId ? "Özgeçmiş Düzenle" : "Yeni Özgeçmiş Ekle"}</DialogTitle>
                </DialogHeader>

                {isResumeLoading ? (
                    <div>Yükleniyor...</div>
                ) : (
                    <>
                        {resumeId ? (
                            <Tabs defaultValue="general" className="w-full">
                                <TabsList className="grid w-full grid-cols-5">
                                    <TabsTrigger value="general">Genel</TabsTrigger>
                                    <TabsTrigger value="education">Eğitim</TabsTrigger>
                                    <TabsTrigger value="experience">Deneyim</TabsTrigger>
                                    <TabsTrigger value="skills">Yetenek</TabsTrigger>
                                    <TabsTrigger value="knowledge">Bilgi</TabsTrigger>
                                </TabsList>

                                <TabsContent value="general" className="mt-4">
                                    <Form {...form}>
                                        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                            {/* Same form fields as create mode */}
                                            <FormField
                                                control={form.control}
                                                name="title"
                                                render={({ field }) => (
                                                    <FormItem>
                                                        <FormLabel>Başlık (Örn: Resume)</FormLabel>
                                                        <FormControl>
                                                            <Input placeholder="Sayfa başlığı..." {...field} />
                                                        </FormControl>
                                                        <FormMessage />
                                                    </FormItem>
                                                )}
                                            />

                                            <FormField
                                                control={form.control}
                                                name="title_sub"
                                                render={({ field }) => (
                                                    <FormItem>
                                                        <FormLabel>Alt Başlık</FormLabel>
                                                        <FormControl>
                                                            <Input placeholder="Kısa açıklama..." {...field} />
                                                        </FormControl>
                                                        <FormMessage />
                                                    </FormItem>
                                                )}
                                            />

                                            <div className="grid grid-cols-2 gap-4">
                                                <FormField
                                                    control={form.control}
                                                    name="education"
                                                    render={({ field }) => (
                                                        <FormItem>
                                                            <FormLabel>Eğitim Bölüm Başlığı</FormLabel>
                                                            <FormControl>
                                                                <Input {...field} />
                                                            </FormControl>
                                                            <FormMessage />
                                                        </FormItem>
                                                    )}
                                                />

                                                <FormField
                                                    control={form.control}
                                                    name="experience"
                                                    render={({ field }) => (
                                                        <FormItem>
                                                            <FormLabel>Deneyim Bölüm Başlığı</FormLabel>
                                                            <FormControl>
                                                                <Input {...field} />
                                                            </FormControl>
                                                            <FormMessage />
                                                        </FormItem>
                                                    )}
                                                />

                                                <FormField
                                                    control={form.control}
                                                    name="coding_skills"
                                                    render={({ field }) => (
                                                        <FormItem>
                                                            <FormLabel>Yetenekler Bölüm Başlığı</FormLabel>
                                                            <FormControl>
                                                                <Input {...field} />
                                                            </FormControl>
                                                            <FormMessage />
                                                        </FormItem>
                                                    )}
                                                />

                                                <FormField
                                                    control={form.control}
                                                    name="knowledge"
                                                    render={({ field }) => (
                                                        <FormItem>
                                                            <FormLabel>Bilgi Bölüm Başlığı</FormLabel>
                                                            <FormControl>
                                                                <Input {...field} />
                                                            </FormControl>
                                                            <FormMessage />
                                                        </FormItem>
                                                    )}
                                                />
                                            </div>

                                            <FormField
                                                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 özgeçmişi sitede görünür yap.
                                                            </FormDescription>
                                                        </div>
                                                        <FormControl>
                                                            <Switch
                                                                checked={field.value}
                                                                onCheckedChange={field.onChange}
                                                            />
                                                        </FormControl>
                                                    </FormItem>
                                                )}
                                            />

                                            <div className="flex justify-end gap-2 pt-4">
                                                <Button type="submit" disabled={updateResume.isPending}>
                                                    Değişiklikleri Kaydet
                                                </Button>
                                            </div>
                                        </form>
                                    </Form>
                                </TabsContent>

                                <TabsContent value="education" className="mt-4">
                                    <EducationList resumeId={resumeId} />
                                </TabsContent>
                                <TabsContent value="experience" className="mt-4">
                                    <ExperienceList resumeId={resumeId} />
                                </TabsContent>
                                <TabsContent value="skills" className="mt-4">
                                    <SkillList resumeId={resumeId} />
                                </TabsContent>
                                <TabsContent value="knowledge" className="mt-4">
                                    <KnowledgeList resumeId={resumeId} />
                                </TabsContent>
                            </Tabs>
                        ) : (
                            <Form {...form}>
                                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                                    <FormField
                                        control={form.control}
                                        name="title"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Başlık (Örn: Resume)</FormLabel>
                                                <FormControl>
                                                    <Input placeholder="Sayfa başlığı..." {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={form.control}
                                        name="title_sub"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Alt Başlık</FormLabel>
                                                <FormControl>
                                                    <Input placeholder="Kısa açıklama..." {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <div className="grid grid-cols-2 gap-4">
                                        <FormField
                                            control={form.control}
                                            name="education"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>Eğitim Bölüm Başlığı</FormLabel>
                                                    <FormControl>
                                                        <Input {...field} />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="experience"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>Deneyim Bölüm Başlığı</FormLabel>
                                                    <FormControl>
                                                        <Input {...field} />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="coding_skills"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>Yetenekler Bölüm Başlığı</FormLabel>
                                                    <FormControl>
                                                        <Input {...field} />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />

                                        <FormField
                                            control={form.control}
                                            name="knowledge"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel>Bilgi Bölüm Başlığı</FormLabel>
                                                    <FormControl>
                                                        <Input {...field} />
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />
                                    </div>

                                    <FormField
                                        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 özgeçmişi sitede görünür yap.
                                                    </FormDescription>
                                                </div>
                                                <FormControl>
                                                    <Switch
                                                        checked={field.value}
                                                        onCheckedChange={field.onChange}
                                                    />
                                                </FormControl>
                                            </FormItem>
                                        )}
                                    />

                                    <div className="flex justify-end gap-2 pt-4">
                                        <Button type="button" variant="outline" onClick={onClose}>
                                            İptal
                                        </Button>
                                        <Button type="submit" disabled={createResume.isPending}>
                                            Oluştur
                                        </Button>
                                    </div>
                                </form>
                            </Form>
                        )}
                    </>
                )}
            </DialogContent>
        </Dialog>
    )
}
