import { useState } from "react"
import { useSkills, useCreateSkill, useUpdateSkill, useDeleteSkill } from "@/features/resume/hooks/useSkills"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
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"
import { Slider } from "@/components/ui/slider"

interface SkillListProps {
    resumeId: string
}

export const SkillList = ({ resumeId }: SkillListProps) => {
    const { data: skills, isLoading } = useSkills(resumeId)
    const deleteSkill = useDeleteSkill()
    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 yeteneği silmek istediğinize emin misiniz?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Evet, Sil",
            cancelButtonText: "İptal",
            confirmButtonColor: "#EF4444",
        })

        if (result.isConfirmed) {
            deleteSkill.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="grid grid-cols-1 md:grid-cols-2 gap-4">
                {skills?.map((skill) => (
                    <div key={skill.id} className="flex justify-between items-center border p-4 rounded-lg bg-card text-card-foreground shadow-sm">
                        <div className="space-y-1 flex-1">
                            <h4 className="font-semibold text-lg">{skill.title}</h4>
                            <div className="flex items-center gap-2">
                                <div className="h-2 w-full bg-secondary rounded-full overflow-hidden max-w-[150px]">
                                    <div className="h-full bg-primary" style={{ width: `${skill.degree}%` }} />
                                </div>
                                <span className="text-sm text-muted-foreground">%{skill.degree}</span>
                            </div>
                            <div className="pt-1">
                                {skill.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(skill)}>
                                <Pencil className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="icon" className="text-red-500 hover:text-red-600" onClick={() => handleDelete(skill.id)}>
                                <Trash2 className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>
                ))}

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

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

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

const SkillDialog = ({ isOpen, onClose, resumeId, initialData }: SkillDialogProps) => {
    const createSkill = useCreateSkill()
    const updateSkill = useUpdateSkill()

    const [title, setTitle] = useState("")
    const [degree, setDegree] = useState(50)
    const [isActive, setIsActive] = useState(false)

    const handleOpenChange = (open: boolean) => {
        if (open) {
            if (initialData) {
                setTitle(initialData.title)
                setDegree(initialData.degree)
                setIsActive(initialData.is_active)
            } else {
                setTitle("")
                setDegree(50)
                setIsActive(false)
            }
        }
        if (!open) onClose()
    }

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

        if (initialData) {
            updateSkill.mutate(
                { id: initialData.id, data },
                { onSuccess: onClose }
            )
        } else {
            createSkill.mutate(data, { onSuccess: onClose })
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={handleOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>{initialData ? "Yetenek Güncelle" : "Yeni Yetenek Ekle"}</DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit} className="space-y-6 py-4">
                    <div className="space-y-2">
                        <Label>Yetenek Adı</Label>
                        <Input value={title} onChange={(e) => setTitle(e.target.value)} required placeholder="Örn: Golang" />
                    </div>
                    <div className="space-y-4">
                        <div className="flex justify-between">
                            <Label>Derece (%)</Label>
                            <span className="text-sm text-muted-foreground">%{degree}</span>
                        </div>
                        <Slider
                            defaultValue={[degree]}
                            max={100}
                            step={5}
                            onValueChange={(vals: number[]) => setDegree(vals[0])}
                        />
                    </div>
                    <div className="flex items-center space-x-2">
                        <Switch id="active-mode-skill" checked={isActive} onCheckedChange={setIsActive} />
                        <Label htmlFor="active-mode-skill">Aktif</Label>
                    </div>
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={onClose}>İptal</Button>
                        <Button type="submit" disabled={createSkill.isPending || updateSkill.isPending}>
                            {initialData ? "Güncelle" : "Ekle"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    )
}
