"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { Plus, Edit, Trash2, Loader2 } from "lucide-react";

type Project = { id: string; title: string; status: string; featured: boolean; createdAt: string; category?: { name: string } | null };

export default function AdminProjectsPage() {
    const [projects, setProjects] = useState<Project[]>([]);
    const [loading, setLoading] = useState(true);
    const [deleting, setDeleting] = useState<string | null>(null);

    const fetchProjects = useCallback(async () => {
        setLoading(true);
        try {
            const res = await fetch("/api/projects");
            const data = await res.json();
            setProjects(Array.isArray(data) ? data : []);
        } catch { setProjects([]); }
        finally { setLoading(false); }
    }, []);

    useEffect(() => { fetchProjects(); }, [fetchProjects]);

    const handleDelete = async (id: string, title: string) => {
        if (!confirm(`Supprimer le projet "${title}" ? Cette action est irréversible.`)) return;
        setDeleting(id);
        try {
            await fetch(`/api/projects/${id}`, { method: "DELETE" });
            setProjects(prev => prev.filter(p => p.id !== id));
        } catch { alert("Erreur lors de la suppression"); }
        finally { setDeleting(null); }
    };

    return (
        <div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "2.5rem" }}>
                <div>
                    <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a" }}>Projets</h1>
                    <p style={{ color: "#64748b" }}>{projects.length} projet(s) au total.</p>
                </div>
                <Link href="/admin/projects/new" style={{ display: "flex", alignItems: "center", gap: "0.5rem", padding: "0.75rem 1.5rem", background: "#2563eb", color: "#fff", borderRadius: "0.875rem", fontWeight: 800, textDecoration: "none", boxShadow: "0 4px 16px rgba(37,99,235,0.3)" }}>
                    <Plus size={18} /> Nouveau Projet
                </Link>
            </div>

            <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} style={{ color: "#2563eb", animation: "spin 1s linear infinite" }} />
                    </div>
                ) : projects.length === 0 ? (
                    <div style={{ textAlign: "center", padding: "4rem", color: "#94a3b8" }}>
                        <p style={{ fontWeight: 700, fontSize: "1.1rem" }}>Aucun projet</p>
                        <p>Créez votre premier projet dès maintenant.</p>
                    </div>
                ) : (
                    <div style={{ overflowX: "auto" }}>
                        <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 600 }}>
                            <thead>
                                <tr style={{ background: "#f8fafc", borderBottom: "1px solid #e2e8f0" }}>
                                    {["Titre", "Catégorie", "Statut", "Vedette", "Date", "Actions"].map(h => (
                                        <th key={h} style={{ padding: "1rem 1.25rem", textAlign: "left", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.07em", color: "#94a3b8", whiteSpace: "nowrap" }}>{h}</th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {projects.map(p => (
                                    <tr key={p.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                                        <td style={{ padding: "1rem 1.25rem", fontWeight: 800, color: "#0f172a", maxWidth: 200 }}>{p.title}</td>
                                        <td style={{ padding: "1rem 1.25rem", color: "#64748b", fontSize: "0.875rem" }}>{p.category?.name || "—"}</td>
                                        <td style={{ padding: "1rem 1.25rem" }}>
                                            <span style={{ padding: "0.3rem 0.85rem", borderRadius: 50, fontSize: "0.75rem", fontWeight: 900, background: p.status === "Terminé" ? "rgba(34,197,94,0.1)" : "rgba(245,158,11,0.1)", color: p.status === "Terminé" ? "#16a34a" : "#d97706" }}>
                                                {p.status}
                                            </span>
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem", fontSize: "1.1rem" }}>{p.featured ? "⭐" : "—"}</td>
                                        <td style={{ padding: "1rem 1.25rem", color: "#94a3b8", fontSize: "0.85rem", whiteSpace: "nowrap" }}>
                                            {new Date(p.createdAt).toLocaleDateString("fr-FR")}
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem" }}>
                                            <div style={{ display: "flex", gap: "0.5rem" }}>
                                                <Link href={`/admin/projects/${p.id}/edit`}
                                                    style={{ width: 34, height: 34, borderRadius: 8, background: "#f1f5f9", border: "1px solid #e2e8f0", display: "flex", alignItems: "center", justifyContent: "center", color: "#475569" }}>
                                                    <Edit size={15} />
                                                </Link>
                                                <button onClick={() => handleDelete(p.id, p.title)} disabled={deleting === p.id}
                                                    style={{ width: 34, height: 34, borderRadius: 8, background: "rgba(239,68,68,0.06)", border: "1px solid rgba(239,68,68,0.2)", display: "flex", alignItems: "center", justifyContent: "center", color: "#ef4444", cursor: "pointer" }}>
                                                    {deleting === p.id ? <Loader2 size={14} style={{ animation: "spin 1s linear infinite" }} /> : <Trash2 size={15} />}
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
            <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
        </div>
    );
}
