import { useState } from "react"
import { useExperiences, useCreateExperience, useUpdateExperience, useDeleteExperience } from "@/features/resume/hooks/useExperiences"
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 ExperienceListProps {
    resumeId: string
}

export const ExperienceList = ({ resumeId }: ExperienceListProps) => {
    const { data: experiences, isLoading } = useExperiences(resumeId)
    const deleteExperience = useDeleteExperience()
    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 deneyim bilgisini silmek istediğinize emin misiniz?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Evet, Sil",
            cancelButtonText: "İptal",
            confirmButtonColor: "#EF4444",
        })

        if (result.isConfirmed) {
            deleteExperience.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">
                {experiences?.map((exp) => (
                    <div key={exp.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">{exp.title}</h4>
                            <p className="text-sm text-muted-foreground">{exp.between_years}</p>
                            <p className="text-sm pt-2">{exp.content}</p>
                            <div className="pt-2">
                                {exp.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(exp)}>
                                <Pencil className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="icon" className="text-red-500 hover:text-red-600" onClick={() => handleDelete(exp.id)}>
                                <Trash2 className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>
                ))}

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

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

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

const ExperienceDialog = ({ isOpen, onClose, resumeId, initialData }: ExperienceDialogProps) => {
    const createExperience = useCreateExperience()
    const updateExperience = useUpdateExperience()

    const [title, setTitle] = useState("")
    const [betweenYears, setBetweenYears] = useState("")
    const [content, setContent] = useState("")
    const [isActive, setIsActive] = useState(false)

    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) {
            updateExperience.mutate(
                { id: initialData.id, data },
                { onSuccess: onClose }
            )
        } else {
            createExperience.mutate(data, { onSuccess: onClose })
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={handleOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>{initialData ? "Deneyim Güncelle" : "Yeni Deneyim Ekle"}</DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit} className="space-y-4 py-4">
                    <div className="space-y-2">
                        <Label>Başlık / Pozisyon</Label>
                        <Input value={title} onChange={(e) => setTitle(e.target.value)} required placeholder="Örn: Kıdemli Yazılım Mühendisi" />
                    </div>
                    <div className="space-y-2">
                        <Label>Yıllar</Label>
                        <Input value={betweenYears} onChange={(e) => setBetweenYears(e.target.value)} required placeholder="Örn: 2020 - Günümüz" />
                    </div>
                    <div className="space-y-2">
                        <Label>Açıklama</Label>
                        <Textarea value={content} onChange={(e) => setContent(e.target.value)} required placeholder="İş tanımı ve sorumluluklar..." />
                    </div>
                    <div className="flex items-center space-x-2">
                        <Switch id="active-mode-exp" checked={isActive} onCheckedChange={setIsActive} />
                        <Label htmlFor="active-mode-exp">Aktif</Label>
                    </div>
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={onClose}>İptal</Button>
                        <Button type="submit" disabled={createExperience.isPending || updateExperience.isPending}>
                            {initialData ? "Güncelle" : "Ekle"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    )
}
