"use client";

import { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";
import { ArrowLeft, Loader2, Save, Image as ImageIcon, X } 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 EditServicePage({ params }: { params: Promise<{ id: string }> }) {
    const router = useRouter();
    const { id } = use(params);
    const [form, setForm] = useState({
        title: "", description: "", images: [] as string[]
    });
    const [fetching, setFetching] = useState(true);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState("");
    const [showMediaLibrary, setShowMediaLibrary] = useState(false);

    useEffect(() => {
        fetch(`/api/services/${id}`)
            .then(res => res.json())
            .then(data => {
                if (data) setForm({ title: data.title, description: data.description, images: data.images || [] });
            })
            .finally(() => setFetching(false));
    }, [id]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true); setError("");
        try {
            const res = await fetch(`/api/services/${id}`, {
                method: "PUT",
                body: JSON.stringify(form),
                headers: { "Content-Type": "application/json" }
            });
            if (res.ok) { router.push("/admin/services"); }
            else { const d = await res.json(); setError(d.error || "Erreur lors de la mise à jour"); }
        } catch { setError("Erreur réseau"); }
        finally { setLoading(false); }
    };

    const addImage = (url: string) => {
        if (!form.images.includes(url)) {
            setForm({ ...form, images: [...form.images, url] });
        }
        setShowMediaLibrary(false);
    };

    const removeImage = (url: string) => {
        setForm({ ...form, images: form.images.filter(img => img !== url) });
    };

    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 (fetching) return <div style={{ display: "flex", justifyContent: "center", padding: "5rem" }}><Loader2 className="animate-spin" size={32} color="#2563eb" /></div>;

    return (
        <div>
            {showMediaLibrary && (
                <MediaLibrary
                    onSelect={addImage}
                    onClose={() => setShowMediaLibrary(false)}
                />
            )}

            <div style={{ display: "flex", alignItems: "center", gap: "1rem", marginBottom: "2.5rem" }}>
                <Link href="/admin/services" 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 Service</h1>
                    <p style={{ color: "#64748b" }}>Mettez à jour les détails de votre prestation.</p>
                </div>
            </div>

            <form onSubmit={handleSubmit}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2rem" }} className="form-grid">
                    <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: "1.25rem", padding: "2rem", display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                        <div>
                            <label style={labelStyle}>Titre du service *</label>
                            <input type="text" required value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} style={inputStyle} />
                        </div>
                        <div>
                            <label style={labelStyle}>Description détaillée *</label>
                            <RichEditor
                                value={form.description}
                                onChange={(description) => setForm({ ...form, description })}
                            />
                        </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", color: "#0f172a", marginBottom: "1.25rem" }}>Galerie d'images</h2>

                            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(80px, 1fr))", gap: "0.75rem", marginBottom: "1.25rem" }}>
                                {form.images.map(url => (
                                    <div key={url} style={{ position: "relative", aspectRatio: "1", borderRadius: "0.5rem", overflow: "hidden", border: "1px solid #e2e8f0" }}>
                                        <Image src={getDirectDriveLink(url)} alt="" fill style={{ objectFit: "cover" }} />
                                        <button type="button" onClick={() => removeImage(url)} style={{ position: "absolute", top: 2, right: 2, background: "rgba(239,68,68,0.9)", color: "white", border: "none", borderRadius: "50%", width: 20, height: 20, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", padding: 0 }}>
                                            <X size={12} />
                                        </button>
                                    </div>
                                ))}
                                <button type="button" onClick={() => setShowMediaLibrary(true)} style={{ aspectRatio: "1", borderRadius: "0.5rem", border: "2px dashed #cbd5e1", background: "#f8fafc", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", color: "#94a3b8" }}>
                                    <ImageIcon size={24} />
                                </button>
                            </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={loading} 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)" }}>
                            {loading ? <Loader2 size={20} className="animate-spin" /> : <Save size={20} />} Enregistrer les modifications
                        </button>
                    </div>
                </div>
            </form>
            <style>{`@media(min-width:900px){.form-grid{grid-template-columns:2fr 1fr !important;}}`}</style>
        </div>
    );
}
