"use client";

import { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft, Loader2, Save, Image as ImageIcon } from "lucide-react";
import Link from "next/link";
import MediaLibrary from "@/components/MediaLibrary";
import Image from "next/image";

export default function EditExperiencePage({ params }: { params: Promise<{ id: string }> }) {
    const router = useRouter();
    const { id } = use(params);

    const [form, setForm] = useState({
        company: "", position: "", location: "",
        startDate: "", endDate: "", current: false,
        description: "", image: ""
    });
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState("");
    const [showMediaLibrary, setShowMediaLibrary] = useState(false);

    useEffect(() => {
        const fetchExperience = async () => {
            try {
                const res = await fetch(`/api/experiences/${id}`);
                const data = await res.json();
                if (data) setForm(data);
            } catch (err) {
                setError("Erreur lors du chargement");
            } finally {
                setLoading(false);
            }
        };
        fetchExperience();
    }, [id]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true); setError("");
        try {
            const res = await fetch(`/api/experiences/${id}`, {
                method: "PUT",
                body: JSON.stringify(form),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) {
                router.push("/admin/experiences");
            } else {
                setError("Erreur lors de la modification");
            }
        } catch {
            setError("Erreur réseau");
        } finally {
            setSaving(false);
        }
    };

    const inputStyle = { width: "100%", padding: "0.875rem 1rem", border: "1.5px solid #e2e8f0", borderRadius: "0.75rem", background: "#f8fafc", fontSize: "0.95rem", outline: "none", boxSizing: "border-box" as const, color: "#0f172a" };
    const labelStyle = { display: "block", marginBottom: "0.5rem", fontSize: "0.78rem", fontWeight: 800, textTransform: "uppercase" as const, letterSpacing: "0.08em", color: "#64748b" };

    if (loading) {
        return (
            <div style={{ display: "flex", justifyContent: "center", alignItems: "center", minHeight: "50vh" }}>
                <Loader2 size={40} className="animate-spin" style={{ color: "#2563eb" }} />
            </div>
        );
    }

    return (
        <div>
            {showMediaLibrary && (
                <MediaLibrary
                    onSelect={(url) => { setForm({ ...form, image: url }); setShowMediaLibrary(false); }}
                    onClose={() => setShowMediaLibrary(false)}
                />
            )}

            <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "2.5rem" }}>
                <Link href="/admin/experiences" style={{ width: 40, height: 40, borderRadius: 12, background: "#fff", border: "1px solid #e2e8f0", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <ArrowLeft size={18} />
                </Link>
                <div>
                    <h1 style={{ fontFamily: "Outfit", fontSize: "2rem", fontWeight: 900, color: "#0f172a" }}>Modifier l'Expérience</h1>
                    <p style={{ color: "#64748b" }}>Mettez à jour votre parcours professionnel.</p>
                </div>
            </div>

            <form onSubmit={handleSubmit}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2rem" }} className="exp-grid">
                    <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "2rem", display: "flex", flexDirection: "column", gap: "1.25rem" }}>
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.25rem" }}>
                            <div>
                                <label style={labelStyle}>Poste *</label>
                                <input type="text" required value={form.position} onChange={e => setForm({ ...form, position: e.target.value })} style={inputStyle} placeholder="ex: Développeur IoT" />
                            </div>
                            <div>
                                <label style={labelStyle}>Entreprise *</label>
                                <input type="text" required value={form.company} onChange={e => setForm({ ...form, company: e.target.value })} style={inputStyle} placeholder="ex: Meta Lab Africa" />
                            </div>
                        </div>

                        <div>
                            <label style={labelStyle}>Lieu</label>
                            <input type="text" value={form.location || ""} onChange={e => setForm({ ...form, location: e.target.value })} style={inputStyle} placeholder="ex: Cotonou, Bénin" />
                        </div>

                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1.25rem" }}>
                            <div>
                                <label style={labelStyle}>Date de début *</label>
                                <input type="text" required value={form.startDate} onChange={e => setForm({ ...form, startDate: e.target.value })} style={inputStyle} placeholder="ex: Janvier 2023" />
                            </div>
                            <div>
                                <label style={labelStyle}>Date de fin</label>
                                <input type="text" disabled={form.current} value={form.current ? "" : (form.endDate || "")} onChange={e => setForm({ ...form, endDate: e.target.value })} style={{ ...inputStyle, opacity: form.current ? 0.5 : 1 }} placeholder="ex: Présent" />
                            </div>
                        </div>

                        <div style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "1rem", background: "#f8fafc", borderRadius: "0.75rem" }}>
                            <input type="checkbox" id="current" checked={form.current} onChange={e => setForm({ ...form, current: e.target.checked })} style={{ width: 18, height: 18, accentColor: "#2563eb" }} />
                            <label htmlFor="current" style={{ fontWeight: 700, color: "#0f172a", cursor: "pointer" }}>Poste actuel</label>
                        </div>

                        <div>
                            <label style={labelStyle}>Description (optionnel)</label>
                            <textarea rows={6} value={form.description || ""} onChange={e => setForm({ ...form, description: e.target.value })} style={{ ...inputStyle, resize: "vertical" }} placeholder="Décrivez vos missions et réalisations..." />
                        </div>
                    </div>

                    <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                        <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "2rem" }}>
                            <label style={labelStyle}>Logo / Image</label>
                            <div onClick={() => setShowMediaLibrary(true)} style={{ width: "100%", height: "10rem", background: "#f8fafc", border: "2px dashed #cbd5e1", borderRadius: "0.75rem", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", position: "relative", overflow: "hidden" }}>
                                {form.image ? (
                                    <Image src={form.image} alt="Logo" fill style={{ objectFit: "contain" }} />
                                ) : (
                                    <div style={{ textAlign: "center", color: "#94a3b8" }}>
                                        <ImageIcon size={32} style={{ margin: "0 auto 0.5rem" }} />
                                        <p style={{ fontSize: "0.75rem", fontWeight: 700 }}>Choisir image</p>
                                    </div>
                                )}
                            </div>
                        </div>

                        {error && <div style={{ color: "#ef4444", fontWeight: 700, fontSize: "0.85rem", textAlign: "center" }}>{error}</div>}

                        <button type="submit" disabled={saving} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "0.6rem", padding: "1.1rem", background: "#2563eb", color: "#fff", border: "none", borderRadius: "0.875rem", fontWeight: 900, fontSize: "1rem", cursor: "pointer", boxShadow: "0 4px 16px rgba(37,99,235,0.3)" }}>
                            {saving ? <><Loader2 size={20} className="animate-spin" /> Envoi...</> : <><Save size={20} /> Enregistrer</>}
                        </button>
                    </div>
                </div>
            </form>
            <style>{`@media(min-width:900px){.exp-grid{grid-template-columns:2fr 1fr !important;}}`}</style>
        </div>
    );
}
