"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 EditProjectPage({ params }: { params: Promise<{ id: string }> }) {
    const router = useRouter();
    const { id } = use(params);

    const [form, setForm] = useState({
        title: "", description: "", categoryId: "", status: "En cours",
        image: "", videoUrl: "", repoUrl: "", liveUrl: "",
        technologies: "", featured: 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, projRes] = await Promise.all([
                    fetch("/api/categories"),
                    fetch(`/api/projects/${id}`)
                ]);
                const cats = await catsRes.json();
                const proj = await projRes.json();
                setCategories(cats);
                if (proj) {
                    setForm({
                        ...proj,
                        technologies: Array.isArray(proj.technologies) ? proj.technologies.join(", ") : "",
                        categoryId: proj.categoryId || ""
                    });
                }
            } 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 payload = {
                ...form,
                technologies: form.technologies.split(",").map(t => t.trim()).filter(Boolean)
            };
            const res = await fetch(`/api/projects/${id}`, {
                method: "PUT",
                body: JSON.stringify(payload),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) {
                router.push("/admin/projects");
            } 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: "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} style={{ color: "var(--primary)", animation: "spin 1s linear infinite" }} />
            </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/projects" 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 le Projet</h1>
                    <p style={{ color: "#64748b" }}>Mettez à jour les informations de votre projet.</p>
                </div>
            </div>

            <form onSubmit={handleSubmit}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2rem" }} className="project-form-grid">
                    <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "2rem", display: "flex", flexDirection: "column", gap: "1.25rem" }}>
                        <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.1rem", color: "#0f172a" }}>Informations du Projet</h2>
                        <div>
                            <label style={labelStyle}>Titre *</label>
                            <input type="text" required value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} style={inputStyle} placeholder="Nom du projet" />
                        </div>
                        <div>
                            <label style={labelStyle}>Description *</label>
                            <RichEditor
                                value={form.description}
                                onChange={(description) => setForm({ ...form, description })}
                                placeholder="Décrivez le projet..."
                            />
                        </div>
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "1rem" }}>
                            <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>
                                <label style={labelStyle}>Statut</label>
                                <select value={form.status} onChange={e => setForm({ ...form, status: e.target.value })} style={inputStyle}>
                                    <option value="En cours">En cours</option>
                                    <option value="Terminé">Terminé</option>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label style={labelStyle}>Technologies (séparées par des virgules)</label>
                            <input type="text" value={form.technologies} onChange={e => setForm({ ...form, technologies: e.target.value })} style={inputStyle} placeholder="ESP32, React, ..." />
                        </div>
                    </div>

                    <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                        <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "2rem", display: "flex", flexDirection: "column", gap: "1.25rem" }}>
                            <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.1rem", color: "#0f172a" }}>Image & Liens</h2>

                            {/* Image Selector */}
                            <div>
                                <label style={labelStyle}>Image de couverture</label>
                                <div onClick={() => setShowMediaLibrary(true)} style={{ width: "100%", height: "12rem", 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={getDirectDriveLink(form.image)} alt="Preview" fill style={{ objectFit: "cover" }} />
                                    ) : (
                                        <div style={{ textAlign: "center", color: "#94a3b8" }}>
                                            <ImageIcon size={32} style={{ margin: "0 auto 0.5rem" }} />
                                            <p style={{ fontSize: "0.8rem", fontWeight: 700 }}>Choisir ou importer</p>
                                        </div>
                                    )}
                                </div>
                                <input type="text" value={form.image} onChange={e => setForm({ ...form, image: e.target.value })} style={{ ...inputStyle, marginTop: "0.5rem", fontSize: "0.8rem" }} placeholder="URL de l'image..." />
                            </div>

                            <div>
                                <label style={labelStyle}>Vidéo YouTube (URL)</label>
                                <input type="url" value={form.videoUrl} onChange={e => setForm({ ...form, videoUrl: e.target.value })} style={inputStyle} />
                            </div>
                            <div>
                                <label style={labelStyle}>Dépôt GitHub (URL)</label>
                                <input type="url" value={form.repoUrl} onChange={e => setForm({ ...form, repoUrl: e.target.value })} style={inputStyle} />
                            </div>
                            <div>
                                <label style={labelStyle}>Lien de démonstration (URL)</label>
                                <input type="url" value={form.liveUrl} onChange={e => setForm({ ...form, liveUrl: e.target.value })} style={inputStyle} placeholder="https://..." />
                            </div>
                            <div style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "1rem", background: "#f8fafc", borderRadius: "0.75rem" }}>
                                <input type="checkbox" id="featured" checked={form.featured} onChange={e => setForm({ ...form, featured: e.target.checked })} style={{ width: 18, height: 18, accentColor: "#2563eb" }} />
                                <label htmlFor="featured" style={{ fontWeight: 700, color: "#0f172a", cursor: "pointer" }}>⭐ Projet en vedette</label>
                            </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", fontSize: "0.875rem", 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" /> Enregistrement...</> : <><Save size={20} /> Enregistrer les modifications</>}
                        </button>
                    </div>
                </div>
            </form>
            <style>{`
                @keyframes spin { to { transform: rotate(360deg); } }
                @media(min-width:900px){.project-form-grid{grid-template-columns:2fr 1fr !important;}}
            `}</style>
        </div>
    );
}
