"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";
import RichEditor from "@/components/RichEditor";
import { getDirectDriveLink } from "@/lib/text";

export default function EditArticlePage({ params }: { params: Promise<{ id: string }> }) {
    const router = useRouter();
    const { id } = use(params);

    const [form, setForm] = useState({
        title: "", content: "", excerpt: "",
        coverImage: "", categoryId: "", published: false
    });
    const [categories, setCategories] = useState<{ id: string; name: string }[]>([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState("");
    const [showMediaLibrary, setShowMediaLibrary] = useState(false);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const [catsRes, artRes] = await Promise.all([
                    fetch("/api/categories"),
                    fetch(`/api/articles/${id}`)
                ]);
                const cats = await catsRes.json();
                const art = await artRes.json();
                setCategories(cats);
                if (art) {
                    setForm({
                        title: art.title || "",
                        content: art.content || "",
                        excerpt: art.excerpt || "",
                        coverImage: art.coverImage || "",
                        categoryId: art.categoryId || "",
                        published: art.published || false
                    });
                }
            } catch (err) {
                setError("Erreur lors du chargement des données");
            } finally {
                setLoading(false);
            }
        };
        fetchData();
    }, [id]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true); setError("");
        try {
            const res = await fetch(`/api/articles/${id}`, {
                method: "PUT",
                body: JSON.stringify(form),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) {
                router.push("/admin/articles");
            } else {
                const d = await res.json();
                setError(d.error || "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: "1rem", outline: "none", boxSizing: "border-box" as const, fontFamily: "Inter, sans-serif", 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} style={{ color: "var(--primary)", animation: "spin 1s linear infinite" }} />
            </div>
        );
    }

    return (
        <div>
            {showMediaLibrary && (
                <MediaLibrary
                    onSelect={(url) => { setForm({ ...form, coverImage: url }); setShowMediaLibrary(false); }}
                    onClose={() => setShowMediaLibrary(false)}
                />
            )}

            <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "2.5rem" }}>
                <Link href="/admin/articles" 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'Article</h1>
                    <p style={{ color: "#64748b" }}>Mettez à jour votre contenu.</p>
                </div>
            </div>

            <form onSubmit={handleSubmit}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2rem" }} className="article-form-grid">
                    <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                        <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "2rem" }}>
                            <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.1rem", marginBottom: "1.5rem", color: "#0f172a" }}>Contenu</h2>
                            <div style={{ display: "flex", flexDirection: "column", gap: "1.25rem" }}>
                                <div>
                                    <label style={labelStyle}>Titre *</label>
                                    <input type="text" required value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} style={inputStyle} />
                                </div>
                                <div>
                                    <label style={labelStyle}>Extrait</label>
                                    <textarea rows={2} value={form.excerpt} onChange={e => setForm({ ...form, excerpt: e.target.value })} style={{ ...inputStyle, resize: "vertical" }} />
                                </div>
                                <div>
                                    <label style={labelStyle}>Texte de l'article *</label>
                                    <RichEditor
                                        value={form.content}
                                        onChange={(content) => setForm({ ...form, content })}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>

                    <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                        <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "2rem" }}>
                            <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.1rem", marginBottom: "1.5rem", color: "#0f172a" }}>Média & Catégorie</h2>
                            <div style={{ display: "flex", flexDirection: "column", gap: "1.25rem" }}>

                                <div>
                                    <label style={labelStyle}>Image de couverture</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.coverImage ? (
                                            <Image src={getDirectDriveLink(form.coverImage)} alt="Cover" fill style={{ objectFit: "cover" }} />
                                        ) : (
                                            <div style={{ textAlign: "center", color: "#94a3b8" }}>
                                                <ImageIcon size={28} style={{ margin: "0 auto 0.5rem" }} />
                                                <p style={{ fontSize: "0.75rem", fontWeight: 700 }}>Choisir image</p>
                                            </div>
                                        )}
                                    </div>
                                    <input type="text" value={form.coverImage} onChange={e => setForm({ ...form, coverImage: e.target.value })} style={{ ...inputStyle, marginTop: "0.5rem", fontSize: "0.8rem" }} placeholder="URL de l'image..." />
                                </div>

                                <div>
                                    <label style={labelStyle}>Catégorie</label>
                                    <select value={form.categoryId} onChange={e => setForm({ ...form, categoryId: e.target.value })} style={inputStyle}>
                                        <option value="">Choisir...</option>
                                        {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                                    </select>
                                </div>

                                <div style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "1rem", background: "#f8fafc", borderRadius: "0.75rem" }}>
                                    <input type="checkbox" id="published" checked={form.published} onChange={e => setForm({ ...form, published: e.target.checked })} style={{ width: 18, height: 18, accentColor: "#2563eb" }} />
                                    <label htmlFor="published" style={{ fontWeight: 700, color: "#0f172a", cursor: "pointer" }}>Publier l'article</label>
                                </div>
                            </div>
                        </div>

                        {error && <div style={{ padding: "0.875rem", background: "rgba(239,68,68,0.08)", border: "1px solid rgba(239,68,68,0.2)", borderRadius: "0.75rem", color: "#dc2626", fontWeight: 600 }}>{error}</div>}

                        <button type="submit" disabled={saving} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "0.6rem", padding: "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>{`
                @keyframes spin { to { transform: rotate(360deg); } }
                @media(min-width:900px){.article-form-grid{grid-template-columns:2fr 1fr !important;}}
            `}</style>
        </div>
    );
}
