import { useState } from "react"
import { useKnowledges, useCreateKnowledge, useUpdateKnowledge, useDeleteKnowledge } from "@/features/resume/hooks/useKnowledges"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Plus, Pencil, Trash2, BookOpen } from "lucide-react"
import Swal from "sweetalert2"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"

interface KnowledgeListProps {
    resumeId: string
}

export const KnowledgeList = ({ resumeId }: KnowledgeListProps) => {
    const { data: knowledges, isLoading } = useKnowledges(resumeId)
    const deleteKnowledge = useDeleteKnowledge()
    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 bilgiyi silmek istediğinize emin misiniz?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Evet, Sil",
            cancelButtonText: "İptal",
            confirmButtonColor: "#EF4444",
        })

        if (result.isConfirmed) {
            deleteKnowledge.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">
                {knowledges?.map((know) => (
                    <div key={know.id} className="flex justify-between items-center border p-4 rounded-lg bg-card text-card-foreground shadow-sm">
                        <div className="flex items-center gap-3">
                            <BookOpen className="h-5 w-5 text-primary" />
                            <div className="space-y-1">
                                <h4 className="font-semibold">{know.title}</h4>
                                <div>
                                    {know.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>
                        <div className="flex gap-2">
                            <Button variant="ghost" size="icon" onClick={() => handleEdit(know)}>
                                <Pencil className="h-4 w-4" />
                            </Button>
                            <Button variant="ghost" size="icon" className="text-red-500 hover:text-red-600" onClick={() => handleDelete(know.id)}>
                                <Trash2 className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>
                ))}

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

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

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

const KnowledgeDialog = ({ isOpen, onClose, resumeId, initialData }: KnowledgeDialogProps) => {
    const createKnowledge = useCreateKnowledge()
    const updateKnowledge = useUpdateKnowledge()

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

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

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

        if (initialData) {
            updateKnowledge.mutate(
                { id: initialData.id, data },
                { onSuccess: onClose }
            )
        } else {
            createKnowledge.mutate(data, { onSuccess: onClose })
        }
    }

    return (
        <Dialog open={isOpen} onOpenChange={handleOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>{initialData ? "Bilgi Güncelle" : "Yeni Bilgi Ekle"}</DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit} className="space-y-4 py-4">
                    <div className="space-y-2">
                        <Label>Bilgi Adı</Label>
                        <Input value={title} onChange={(e) => setTitle(e.target.value)} required placeholder="Örn: Agiles Software Development" />
                    </div>
                    <div className="flex items-center space-x-2">
                        <Switch id="active-mode-know" checked={isActive} onCheckedChange={setIsActive} />
                        <Label htmlFor="active-mode-know">Aktif</Label>
                    </div>
                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={onClose}>İptal</Button>
                        <Button type="submit" disabled={createKnowledge.isPending || updateKnowledge.isPending}>
                            {initialData ? "Güncelle" : "Ekle"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    )
}
