"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { Plus, Edit, Trash2, Loader2, FileText } from "lucide-react";

type Article = {
    id: string;
    title: string;
    published: boolean;
    createdAt: string;
    category?: { name: string } | null
};

export default function AdminArticlesPage() {
    const [articles, setArticles] = useState<Article[]>([]);
    const [loading, setLoading] = useState(true);
    const [deleting, setDeleting] = useState<string | null>(null);

    const fetchArticles = useCallback(async () => {
        setLoading(true);
        try {
            const res = await fetch("/api/articles");
            const data = await res.json();
            setArticles(Array.isArray(data) ? data : []);
        } catch {
            setArticles([]);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        fetchArticles();
    }, [fetchArticles]);

    const handleDelete = async (id: string, title: string) => {
        if (!confirm(`Supprimer l'article "${title}" ?`)) return;
        setDeleting(id);
        try {
            const res = await fetch(`/api/articles/${id}`, { method: "DELETE" });
            if (res.ok) {
                setArticles(prev => prev.filter(a => a.id !== id));
            } else {
                alert("Erreur lors de la suppression");
            }
        } catch {
            alert("Erreur réseau");
        } 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" }}>Articles</h1>
                    <p style={{ color: "#64748b" }}>{articles.length} article(s) publiés ou en brouillon.</p>
                </div>
                <Link href="/admin/articles/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} /> Nouvel Article
                </Link>
            </div>

            <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", overflow: "hidden", boxShadow: "0 1px 4px rgba(0,0,0,0.04)" }}>
                {loading ? (
                    <div style={{ display: "flex", justifyContent: "center", padding: "4rem" }}>
                        <Loader2 size={32} style={{ color: "#2563eb", animation: "spin 1s linear infinite" }} />
                    </div>
                ) : articles.length === 0 ? (
                    <div style={{ textAlign: "center", padding: "5rem", color: "#94a3b8" }}>
                        <FileText size={40} style={{ margin: "0 auto 1rem", opacity: 0.5 }} />
                        <p style={{ fontWeight: 700, fontSize: "1.1rem", marginBottom: "0.5rem" }}>Aucun article</p>
                        <p>Commencez à rédiger pour partager votre expertise.</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", "Date", "Actions"].map(h => (
                                        <th key={h} style={{ padding: "1rem 1.25rem", textAlign: "left", fontWeight: 800, fontSize: "0.78rem", textTransform: "uppercase", letterSpacing: "0.06em", color: "#94a3b8" }}>{h}</th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {articles.map(article => (
                                    <tr key={article.id} style={{ borderBottom: "1px solid #f1f5f9", transition: "background 0.15s" }}>
                                        <td style={{ padding: "1rem 1.25rem", fontWeight: 800, color: "#0f172a" }}>{article.title}</td>
                                        <td style={{ padding: "1rem 1.25rem", color: "#64748b", fontSize: "0.875rem" }}>{article.category?.name || "—"}</td>
                                        <td style={{ padding: "1rem 1.25rem" }}>
                                            <span style={{ padding: "0.3rem 0.85rem", borderRadius: 50, fontSize: "0.75rem", fontWeight: 900, background: article.published ? "rgba(34,197,94,0.1)" : "rgba(100,116,139,0.1)", color: article.published ? "#16a34a" : "#64748b" }}>
                                                {article.published ? "Publié" : "Brouillon"}
                                            </span>
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem", color: "#94a3b8", fontSize: "0.85rem" }}>{new Date(article.createdAt).toLocaleDateString("fr-FR")}</td>
                                        <td style={{ padding: "1rem 1.25rem" }}>
                                            <div style={{ display: "flex", gap: "0.5rem" }}>
                                                <Link href={`/admin/articles/${article.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(article.id, article.title)} disabled={deleting === article.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 === article.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>
    );
}
