import { useState } from "react"
import { useEducations, useCreateEducation, useUpdateEducation, useDeleteEducation } from "@/features/resume/hooks/useEducations"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { Plus, Pencil, Trash2 } from "lucide-react"
import Swal from "sweetalert2"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"

interface EducationListProps {
    resumeId: string
}

export const EducationList = ({ resumeId }: EducationListProps) => {
    const { data: educations, isLoading } = useEducations(resumeId)
    const deleteEducation = useDeleteEducation()
    const [isDialogOpen, setIsDialogOpen] = useState(false)
    const [editingItem, setEditingItem] = useState<any>(null)

    const handleDelete = async (id: string) => {
        const result = await Swal.fire({
            title: "Emin misiniz?",
            text: "Bu eğitim bilgisini silmek istediğinize emin misiniz?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Evet, Sil",
            cancelButtonText: "İptal",
            confirmButtonColor: "#EF4444",
        })

        if (result.isConfirmed) {
            deleteEducation.mutate(id)
        }
    }

    const handleEdit = (item: any) => {
        setEditingItem(item)
        setIsDialogOpen(true)
    }

    const handleCreate = () => {
        setEditingItem(null)
        setIsDialogOpen(true)
    }

    if (isLoading) return <div>Yükleniyor...</div>

    return (
        <div className="space-y-4">
            <div className="flex justify-end">
                <Button onClick={handleCreate} size="sm">
                    <Plus className="mr-2 h-4 w-4" /> Yeni Ekle
                </Button>
            </div>

            <div className="space-y-4">
                {educations?.map((edu) => (
                    <div key={edu.id} className="flex justify-between items-start border p-4 rounded-lg bg-card text-card-foreground shadow-sm">
                        <div className="space-y-1">
                            <h4 className="font-semibold text-lg">{edu.title}</h4>
                            <p className="text-sm text-muted-foreground">{edu.between_years}</p>
                            <p className="text-sm pt-2">{edu.content}</p>
                            <div className="pt-2">
                                {edu.is_active ? (
                                    <span className="text-xs bg-green-100 text-green-800 px-2 py-0.5 rounded-full dark:bg-green-900 dark:text-green-100">Aktif</span>
                                ) : (
                                    <span className="text-xs bg-gray-100 text-gray-800 px-2 py-0.5 rounded-full dark:bg-gray-800 dark:text-gray-100">Pasif</span>
                                )}
                            </div>
                        </div>
                        <div className="flex gap-2">
                            <Button variant="ghost" size="icon" onClick={() => handleEdit(edu)}>
                                <Pencil className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="icon" className="text-red-500 hover:text-red-600" onClick={() => handleDelete(edu.id)}>
                                <Trash2 className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>
                ))}

                {educations?.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground border border-dashed rounded-lg">
                        Henüz eğitim bilgisi eklenmemiş.
                    </div>
                )}
            </div>

            <EducationDialog
                isOpen={isDialogOpen}
                onClose={() => setIsDialogOpen(false)}
                resumeId={resumeId}
                initialData={editingItem}
            />
        </div>
    )
}

interface EducationDialogProps {
    isOpen: boolean
    onClose: () => void
    resumeId: string
    initialData?: any
}

const EducationDialog = ({ isOpen, onClose, resumeId, initialData }: EducationDialogProps) => {
    const createEducation = useCreateEducation()
    const updateEducation = useUpdateEducation()

    // Simple state management for form fields since it's a small form
    const [title, setTitle] = useState("")
    const [betweenYears, setBetweenYears] = useState("")
    const [content, setContent] = useState("")
    const [isActive, setIsActive] = useState(false)

    // Reset or populate form when dialog opens
    useState(() => {
        if (isOpen) {
            if (initialData) {
                setTitle(initialData.title)
                setBetweenYears(initialData.between_years)
                setContent(initialData.content)
                setIsActive(initialData.is_active)
            } else {
                setTitle("")
                setBetweenYears("")
                setContent("")
                setIsActive(false)
            }
        }
    })

    // Update state when initialData changes or dialog re-opens
    const handleOpenChange = (open: boolean) => {
        if (open) {
            if (initialData) {
                setTitle(initialData.title)
                setBetweenYears(initialData.between_years)
                setContent(initialData.content)
                setIsActive(initialData.is_active)
            } else {
                setTitle("")
                setBetweenYears("")
                setContent("")
                setIsActive(false)
            }
        }
        if (!open) onClose()
    }

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault()
        const data = {
            title,
            between_years: betweenYears,
            content,
            is_active: isActive,
            resume_id: resumeId
        }

        if (initialData) {
            updateEducation.mutate(
                { id: initialData.id, data },
                { onSuccess: onClose }
            )
        } else {
            createEducation.mutate(data, { onSuccess: onClose })
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={handleOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>{initialData ? "Eğitim Güncelle" : "Yeni Eğitim Ekle"}</DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit} className="space-y-4 py-4">
                    <div className="space-y-2">
                        <Label>Başlık / Okul</Label>
                        <Input value={title} onChange={(e) => setTitle(e.target.value)} required placeholder="Örn: Bilgisayar Mühendisliği" />
                    </div>
                    <div className="space-y-2">
                        <Label>Yıllar</Label>
                        <Input value={betweenYears} onChange={(e) => setBetweenYears(e.target.value)} required placeholder="Örn: 2018 - 2022" />
                    </div>
                    <div className="space-y-2">
                        <Label>Açıklama</Label>
                        <Textarea value={content} onChange={(e) => setContent(e.target.value)} required placeholder="Bölüm detayları..." />
                    </div>
                    <div className="flex items-center space-x-2">
                        <Switch id="active-mode" checked={isActive} onCheckedChange={setIsActive} />
                        <Label htmlFor="active-mode">Aktif</Label>
                    </div>
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={onClose}>İptal</Button>
                        <Button type="submit" disabled={createEducation.isPending || updateEducation.isPending}>
                            {initialData ? "Güncelle" : "Ekle"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    )
}
