"use client";

import { useState, useEffect } from "react";
import { Plus, Trash2, Loader2, Tag } from "lucide-react";

export default function AdminCategoriesPage() {
    const [categories, setCategories] = useState<any[]>([]);
    const [newName, setNewName] = useState("");
    const [loading, setLoading] = useState(true);
    const [adding, setAdding] = useState(false);
    const [deleting, setDeleting] = useState<string | null>(null);

    const fetchCategories = async () => {
        try {
            const res = await fetch("/api/categories");
            const data = await res.json();
            setCategories(data);
        } catch { }
        finally { setLoading(false); }
    };

    useEffect(() => { fetchCategories(); }, []);

    const handleAdd = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!newName.trim()) return;
        setAdding(true);
        try {
            const res = await fetch("/api/categories", {
                method: "POST",
                body: JSON.stringify({ name: newName }),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) {
                setNewName("");
                fetchCategories();
            } else {
                alert("Erreur lors de l'ajout");
            }
        } catch { }
        finally { setAdding(false); }
    };

    const handleDelete = async (id: string, name: string) => {
        if (!confirm(`Supprimer la catégorie "${name}" ?`)) return;
        setDeleting(id);
        try {
            const res = await fetch(`/api/categories/${id}`, { method: "DELETE" });
            if (res.ok) {
                fetchCategories();
            } else {
                const d = await res.json();
                alert(d.error || "Erreur lors de la suppression");
            }
        } catch { }
        finally { setDeleting(null); }
    };

    return (
        <div>
            <div style={{ marginBottom: "2.5rem" }}>
                <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a" }}>Catégories</h1>
                <p style={{ color: "#64748b" }}>Organisez vos projets et articles par thématiques.</p>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2rem" }} className="cat-grid">
                {/* Form */}
                <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "1.5rem" }}>
                    <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.1rem", color: "#0f172a", marginBottom: "1rem" }}>Ajouter une catégorie</h2>
                    <form onSubmit={handleAdd} style={{ display: "flex", gap: "0.75rem" }}>
                        <input type="text" value={newName} onChange={e => setNewName(e.target.value)} placeholder="ex: Intelligence Artificielle"
                            style={{ flex: 1, padding: "0.875rem 1rem", border: "1.5px solid #e2e8f0", borderRadius: "0.75rem", background: "#f8fafc", fontSize: "0.95rem", outline: "none" }} />
                        <button type="submit" disabled={adding} style={{ padding: "0 1.5rem", background: "#2563eb", color: "#fff", border: "none", borderRadius: "0.75rem", fontWeight: 900, cursor: "pointer", display: "flex", alignItems: "center", gap: "0.5rem" }}>
                            {adding ? <Loader2 size={18} className="animate-spin" /> : <><Plus size={18} /> Ajouter</>}
                        </button>
                    </form>
                </div>

                {/* List */}
                <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", overflow: "hidden" }}>
                    {loading ? (
                        <div style={{ display: "flex", justifyContent: "center", padding: "4rem" }}><Loader2 size={32} className="animate-spin" style={{ color: "#2563eb" }} /></div>
                    ) : (
                        <table style={{ width: "100%", borderCollapse: "collapse" }}>
                            <thead>
                                <tr style={{ background: "#f8fafc", borderBottom: "1px solid #e2e8f0" }}>
                                    <th style={{ padding: "1rem 1.25rem", textAlign: "left", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>Nom</th>
                                    <th style={{ padding: "1rem 1.25rem", textAlign: "center", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>Projets</th>
                                    <th style={{ padding: "1rem 1.25rem", textAlign: "center", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>Articles</th>
                                    <th style={{ padding: "1rem 1.25rem", textAlign: "right", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {categories.map(c => (
                                    <tr key={c.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                                        <td style={{ padding: "1rem 1.25rem", fontWeight: 800, color: "#0f172a" }}>
                                            <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
                                                <Tag size={16} style={{ color: "var(--primary)" }} />
                                                {c.name}
                                            </div>
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem", textAlign: "center", color: "#64748b", fontWeight: 700 }}>{c._count.projects}</td>
                                        <td style={{ padding: "1rem 1.25rem", textAlign: "center", color: "#64748b", fontWeight: 700 }}>{c._count.articles}</td>
                                        <td style={{ padding: "1rem 1.25rem", textAlign: "right" }}>
                                            <button onClick={() => handleDelete(c.id, c.name)} disabled={deleting === c.id} style={{ width: 34, height: 34, borderRadius: 8, background: "rgba(239,68,68,0.06)", display: "flex", alignItems: "center", justifyContent: "center", color: "#ef4444", cursor: "pointer", border: "none" }}>
                                                {deleting === c.id ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={15} />}
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                                {categories.length === 0 && (
                                    <tr><td colSpan={4} style={{ textAlign: "center", padding: "3rem", color: "#94a3b8" }}>Aucune catégorie définie.</td></tr>
                                )}
                            </tbody>
                        </table>
                    )}
                </div>
            </div>
            <style>{`@media(min-width:900px){.cat-grid{grid-template-columns:1fr !important;}}`}</style>
        </div>
    );
}
