"use client";

import { useState, useEffect } from "react";
import { Plus, Trash2, Loader2, GraduationCap, Image as ImageIcon } from "lucide-react";
import MediaLibrary from "@/components/MediaLibrary";
import Image from "next/image";

export default function AdminEducationPage() {
    const [items, setItems] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [form, setForm] = useState({ school: "", degree: "", startDate: "", endDate: "", description: "", image: "" });
    const [showMediaLibrary, setShowMediaLibrary] = useState(false);

    const fetchEducation = async () => {
        try {
            const res = await fetch("/api/education");
            const data = await res.json();
            setItems(data);
        } catch { }
        finally { setLoading(false); }
    };

    useEffect(() => { fetchEducation(); }, []);

    const handleAdd = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);
        try {
            const res = await fetch("/api/education", {
                method: "POST",
                body: JSON.stringify(form),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) {
                setForm({ school: "", degree: "", startDate: "", endDate: "", description: "", image: "" });
                fetchEducation();
            }
        } catch { }
        finally { setSaving(false); }
    };

    const handleDelete = async (id: string) => {
        if (!confirm("Supprimer cette formation ?")) return;
        try {
            await fetch(`/api/education/${id}`, { method: "DELETE" });
            fetchEducation();
        } catch { }
    };

    const inputStyle = { width: "100%", padding: "0.75rem", border: "1.5px solid #e2e8f0", borderRadius: "0.5rem", background: "#f8fafc", fontSize: "0.9rem", outline: "none" };
    const labelStyle = { display: "block", marginBottom: "0.3rem", fontSize: "0.7rem", fontWeight: 800, textTransform: "uppercase" as const, color: "#64748b" };

    return (
        <div>
            {showMediaLibrary && (
                <MediaLibrary
                    onSelect={(url) => { setForm({ ...form, image: url }); setShowMediaLibrary(false); }}
                    onClose={() => setShowMediaLibrary(false)}
                />
            )}

            <div style={{ marginBottom: "2.5rem" }}>
                <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a" }}>Parcours Académique</h1>
                <p style={{ color: "#64748b" }}>Gérez vos diplômes et formations.</p>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2rem" }}>
                <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "1.5rem" }}>
                    <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.1rem", marginBottom: "1.5rem" }}>Ajouter une formation</h2>
                    <form onSubmit={handleAdd} style={{ display: "flex", flexDirection: "column", gap: "1.25rem" }}>
                        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: "1rem" }}>
                            <div>
                                <label style={labelStyle}>École *</label>
                                <input required value={form.school} onChange={e => setForm({ ...form, school: e.target.value })} style={inputStyle} placeholder="ex: HECM" />
                            </div>
                            <div>
                                <label style={labelStyle}>Diplôme *</label>
                                <input required value={form.degree} onChange={e => setForm({ ...form, degree: e.target.value })} style={inputStyle} placeholder="ex: Licence" />
                            </div>
                        </div>

                        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: "1.25rem" }}>
                            <div style={{ flex: 1 }}>
                                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
                                    <div>
                                        <label style={labelStyle}>Date de début</label>
                                        <input value={form.startDate} onChange={e => setForm({ ...form, startDate: e.target.value })} style={inputStyle} placeholder="ex: 2020" />
                                    </div>
                                    <div>
                                        <label style={labelStyle}>Date de fin</label>
                                        <input value={form.endDate} onChange={e => setForm({ ...form, endDate: e.target.value })} style={inputStyle} placeholder="ex: 2023" />
                                    </div>
                                </div>
                                <div style={{ marginTop: "1rem" }}>
                                    <label style={labelStyle}>Description courte</label>
                                    <input value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} style={inputStyle} placeholder="Bref résumé..." />
                                </div>
                            </div>

                            <div style={{ width: 140 }}>
                                <label style={labelStyle}>Logo / Image</label>
                                <div onClick={() => setShowMediaLibrary(true)} style={{ width: 140, height: 100, borderRadius: "0.75rem", background: "#f8fafc", border: "2px dashed #cbd5e1", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", position: "relative", overflow: "hidden" }}>
                                    {form.image ? (
                                        <Image src={form.image} alt="Logo" fill style={{ objectFit: "contain" }} />
                                    ) : (
                                        <ImageIcon size={24} color="#cbd5e1" />
                                    )}
                                </div>
                            </div>
                        </div>

                        <button type="submit" disabled={saving} style={{ padding: "0.8rem", background: "#2563eb", color: "#fff", border: "none", borderRadius: "0.5rem", fontWeight: 900, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: "0.5rem" }}>
                            {saving ? <Loader2 size={18} className="animate-spin" /> : <><Plus size={18} /> Ajouter au parcours</>}
                        </button>
                    </form>
                </div>

                <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "1.5rem" }}>
                    <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.1rem", marginBottom: "1.5rem" }}>Formations enregistrées</h2>
                    {loading ? <div style={{ textAlign: "center", padding: "2rem" }}><Loader2 size={32} className="animate-spin" style={{ color: "var(--primary)" }} /></div> : (
                        <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
                            {items.map(item => (
                                <div key={item.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "1rem", border: "1px solid #f1f5f9", borderRadius: "1rem", background: "#f8fafc" }}>
                                    <div style={{ display: "flex", alignItems: "center", gap: "1rem" }}>
                                        {item.image && (
                                            <div style={{ width: 50, height: 50, borderRadius: "0.75rem", background: "#fff", border: "1px solid #e2e8f0", position: "relative", overflow: "hidden" }}>
                                                <Image src={item.image} alt="" fill style={{ objectFit: "contain" }} />
                                            </div>
                                        )}
                                        <div>
                                            <p style={{ fontWeight: 800, color: "#0f172a" }}>{item.degree}</p>
                                            <p style={{ fontSize: "0.85rem", color: "#64748b", fontWeight: 600 }}>{item.school} | {item.startDate} - {item.endDate}</p>
                                        </div>
                                    </div>
                                    <button onClick={() => handleDelete(item.id)} style={{ padding: "0.5rem", color: "#ef4444", background: "rgba(239,68,68,0.05)", border: "none", borderRadius: "0.5rem", cursor: "pointer" }}><Trash2 size={18} /></button>
                                </div>
                            ))}
                            {items.length === 0 && <p style={{ color: "#94a3b8", textAlign: "center" }}>Aucune formation enregistrée.</p>}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
