"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { Plus, Edit, Trash2, Loader2, Briefcase } from "lucide-react";
import Image from "next/image";

type Experience = { id: string; company: string; position: string; startDate: string; endDate: string | null; current: boolean; image?: string | null };

export default function AdminExperiencesPage() {
    const [experiences, setExperiences] = useState<Experience[]>([]);
    const [loading, setLoading] = useState(true);
    const [deleting, setDeleting] = useState<string | null>(null);

    const fetchExperiences = useCallback(async () => {
        setLoading(true);
        try {
            const res = await fetch("/api/experiences");
            const data = await res.json();
            setExperiences(Array.isArray(data) ? data : []);
        } catch { setExperiences([]); }
        finally { setLoading(false); }
    }, []);

    useEffect(() => { fetchExperiences(); }, [fetchExperiences]);

    const handleDelete = async (id: string, name: string) => {
        if (!confirm(`Supprimer l'expérience chez "${name}" ?`)) return;
        setDeleting(id);
        try {
            const res = await fetch(`/api/experiences/${id}`, { method: "DELETE" });
            if (res.ok) {
                setExperiences(prev => prev.filter(e => e.id !== id));
            } else {
                alert("Erreur lors de la suppression");
            }
        } 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" }}>Expériences</h1>
                    <p style={{ color: "#64748b" }}>Gérez votre parcours professionnel (CV).</p>
                </div>
                <Link href="/admin/experiences/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" }}>
                    <Plus size={18} /> Nouvelle Expérience
                </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} className="animate-spin" style={{ color: "#2563eb" }} /></div>
                ) : experiences.length === 0 ? (
                    <div style={{ textAlign: "center", padding: "5rem", color: "#94a3b8" }}>
                        <Briefcase size={40} style={{ margin: "0 auto 1rem", opacity: 0.5 }} />
                        <p style={{ fontWeight: 700, fontSize: "1.1rem" }}>Aucune expérience</p>
                    </div>
                ) : (
                    <div style={{ overflowX: "auto" }}>
                        <table style={{ width: "100%", borderCollapse: "collapse" }}>
                            <thead>
                                <tr style={{ background: "#f8fafc", borderBottom: "1px solid #e2e8f0" }}>
                                    {["Poste / Entreprise", "Période", "Actions"].map(h => (
                                        <th key={h} style={{ padding: "1rem 1.25rem", textAlign: "left", fontWeight: 800, fontSize: "0.75rem", textTransform: "uppercase", color: "#94a3b8" }}>{h}</th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {experiences.map(e => (
                                    <tr key={e.id} style={{ borderBottom: "1px solid #f1f5f9" }}>
                                        <td style={{ padding: "1rem 1.25rem" }}>
                                            <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
                                                {e.image && (
                                                    <div style={{ width: 40, height: 40, borderRadius: 8, overflow: "hidden", position: "relative", border: "1px solid #e2e8f0", background: "#fff" }}>
                                                        <Image src={e.image} alt="" fill style={{ objectFit: "contain", padding: 2 }} />
                                                    </div>
                                                )}
                                                <div>
                                                    <p style={{ fontWeight: 800, color: "#0f172a" }}>{e.position}</p>
                                                    <p style={{ fontSize: "0.85rem", color: "#64748b", fontWeight: 600 }}>{e.company}</p>
                                                </div>
                                            </div>
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem", color: "#94a3b8", fontSize: "0.85rem", fontWeight: 600 }}>
                                            {e.startDate} — {e.current ? "Aujourd'hui" : e.endDate}
                                        </td>
                                        <td style={{ padding: "1rem 1.25rem" }}>
                                            <div style={{ display: "flex", gap: "0.5rem" }}>
                                                <Link href={`/admin/experiences/${e.id}/edit`} style={{ width: 34, height: 34, borderRadius: 8, background: "#f1f5f9", display: "flex", alignItems: "center", justifyContent: "center", color: "#475569" }}><Edit size={15} /></Link>
                                                <button onClick={() => handleDelete(e.id, e.company)} disabled={deleting === e.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 === e.id ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={15} />}
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
}
