"use client";

import { useState, useEffect } 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 NewArticlePage() {
    const router = useRouter();
    const [form, setForm] = useState({
        title: "", content: "", excerpt: "",
        coverImage: "", categoryId: "", published: false
    });
    const [categories, setCategories] = useState<{ id: string; name: string }[]>([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    const [showMediaLibrary, setShowMediaLibrary] = useState(false);

    useEffect(() => {
        fetch("/api/categories").then(r => r.json()).then(setCategories).catch(() => { });
    }, []);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true); setError("");
        try {
            const res = await fetch("/api/articles", {
                method: "POST",
                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 création"); }
        } catch { setError("Erreur réseau"); }
        finally { setLoading(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" };

    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" }}>Nouvel Article</h1>
                    <p style={{ color: "#64748b" }}>Créez un nouvel article de blog.</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" }}>Informations</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} placeholder="Titre de l'article" />
                                </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" }} placeholder="Courte description" />
                                </div>
                                <div>
                                    <label style={labelStyle}>Contenu *</label>
                                    <RichEditor
                                        value={form.content}
                                        onChange={(content) => setForm({ ...form, content })}
                                        placeholder="Rédigez votre article ici..."
                                    />
                                </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="">Sans catégorie</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 immédiatement</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, fontSize: "0.875rem" }}>{error}</div>}

                        <button type="submit" disabled={loading} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "0.6rem", padding: "1rem", background: loading ? "#94a3b8" : "#2563eb", color: "#fff", border: "none", borderRadius: "0.875rem", fontWeight: 900, fontSize: "1rem", cursor: loading ? "not-allowed" : "pointer", boxShadow: "0 4px 16px rgba(37,99,235,0.3)" }}>
                            {loading ? <><Loader2 size={20} className="animate-spin" /> Envoi...</> : <><Save size={20} /> Publier l'article</>}
                        </button>
                    </div>
                </div>
            </form>
            <style>{`@media(min-width:900px){.article-form-grid{grid-template-columns:2fr 1fr !important;}}`}</style>
        </div>
    );
}
