"use client";

import { useState, useEffect } from "react";
import { Upload, X, Trash2, Check, Search, Loader2, Image as ImageIcon } from "lucide-react";
import Image from "next/image";
import { getDirectDriveLink } from "@/lib/text";

interface Media {
    id: string;
    url: string;
    name: string;
    type: string;
    size: number;
}

interface MediaLibraryProps {
    onSelect: (url: string) => void;
    onClose: () => void;
}


export default function MediaLibrary({ onSelect, onClose }: MediaLibraryProps) {
    const [media, setMedia] = useState<Media[]>([]);
    const [loading, setLoading] = useState(true);
    const [uploading, setUploading] = useState(false);
    const [searchTerm, setSearchTerm] = useState("");
    const [selectedId, setSelectedId] = useState<string | null>(null);
    const [tab, setTab] = useState<"gallery" | "external">("gallery");
    const [externalUrl, setExternalUrl] = useState("");

    const fetchMedia = async () => {
        setLoading(true);
        try {
            const res = await fetch("/api/media");
            const data = await res.json();
            setMedia(Array.isArray(data) ? data : []);
        } catch { }
        finally { setLoading(false); }
    };

    useEffect(() => { fetchMedia(); }, []);

    const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        setUploading(true);
        const formData = new FormData();
        formData.append("file", file);

        try {
            const res = await fetch("/api/upload", { method: "POST", body: formData });
            if (res.ok) {
                fetchMedia();
            }
        } catch { }
        finally { setUploading(false); }
    };

    const handleDelete = async (e: React.MouseEvent, id: string) => {
        e.stopPropagation();
        if (!confirm("Supprimer ce fichier ?")) return;
        try {
            const res = await fetch(`/api/media?id=${id}`, { method: "DELETE" });
            if (res.ok) {
                setMedia(media.filter(m => m.id !== id));
            }
        } catch { }
    };

    const filteredMedia = media.filter(m => m.name.toLowerCase().includes(searchTerm.toLowerCase()));

    const handleConfirm = () => {
        if (tab === "external" && externalUrl) {
            onSelect(getDirectDriveLink(externalUrl));
        } else if (tab === "gallery" && selectedId) {
            const s = media.find(m => m.id === selectedId);
            if (s) onSelect(s.url);
        }
    };

    return (
        <div style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.8)", backdropFilter: "blur(12px)", zIndex: 9999, display: "flex", alignItems: "center", justifyContent: "center", padding: "10px" }}>
            <div style={{ background: "#fff", width: "100%", maxWidth: "850px", maxHeight: "95vh", borderRadius: "1.5rem", display: "flex", flexDirection: "column", overflow: "hidden", boxShadow: "0 32px 64px -12px rgba(0,0,0,0.3)" }}>
                {/* Header */}
                <div style={{ padding: "1rem 1.5rem", borderBottom: "1px solid #f1f5f9", display: "flex", justifyContent: "space-between", alignItems: "center", background: "#f8fafc" }}>
                    <div>
                        <h2 style={{ fontFamily: "Outfit", fontWeight: 900, fontSize: "1.2rem", color: "#0f172a", margin: 0 }}>Gestionnaire de Médias</h2>
                        <p style={{ fontSize: "0.75rem", color: "#64748b", margin: 0 }}>Gérez vos fichiers ou utilisez des liens externes.</p>
                    </div>
                    <button onClick={onClose} style={{ padding: "0.5rem", borderRadius: "0.5rem", background: "#fff", border: "1px solid #e2e8f0", cursor: "pointer", display: "flex", alignItems: "center" }}><X size={18} color="#64748b" /></button>
                </div>

                {/* Tabs */}
                <div style={{ display: "flex", background: "#f8fafc", padding: "0 1.5rem", gap: "1.5rem", borderBottom: "1px solid #f1f5f9" }}>
                    <button onClick={() => setTab("gallery")} style={{ padding: "0.75rem 0", border: "none", background: "none", color: tab === "gallery" ? "#2563eb" : "#64748b", fontWeight: 800, fontSize: "0.85rem", borderBottom: `2px solid ${tab === "gallery" ? "#2563eb" : "transparent"}`, cursor: "pointer", transition: "all 0.2s" }}>Médiathèque</button>
                    <button onClick={() => setTab("external")} style={{ padding: "0.75rem 0", border: "none", background: "none", color: tab === "external" ? "#2563eb" : "#64748b", fontWeight: 800, fontSize: "0.85rem", borderBottom: `2px solid ${tab === "external" ? "#2563eb" : "transparent"}`, cursor: "pointer", transition: "all 0.2s" }}>Lien Direct (URL)</button>
                </div>

                <div style={{ flex: 1, overflowY: "auto", background: "#fff" }}>
                    {tab === "gallery" ? (
                        <>
                            {/* Toolbar */}
                            <div style={{ padding: "1rem 1.5rem", borderBottom: "1px solid #f1f5f9", display: "flex", gap: "1rem", flexWrap: "wrap", alignItems: "center" }}>
                                <div style={{ flex: 1, position: "relative", minWidth: "200px" }}>
                                    <Search size={16} style={{ position: "absolute", left: "0.75rem", top: "50%", transform: "translateY(-50%)", color: "#94a3b8" }} />
                                    <input type="text" placeholder="Rechercher..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)}
                                        style={{ width: "100%", padding: "0.6rem 0.75rem 0.6rem 2.5rem", border: "1.5px solid #e2e8f0", borderRadius: "0.75rem", fontSize: "0.9rem", outline: "none", background: "#f8fafc", color: "#0f172a" }} />
                                </div>
                                <label style={{ display: "inline-flex", alignItems: "center", gap: "0.5rem", padding: "0.6rem 1.25rem", background: "#2563eb", color: "#fff", borderRadius: "0.75rem", fontWeight: 900, fontSize: "0.85rem", cursor: "pointer", transition: "all 0.2s" }}>
                                    {uploading ? <Loader2 size={16} className="animate-spin" /> : <><Upload size={16} /> Importer</>}
                                    <input type="file" hidden accept="image/*" onChange={handleUpload} disabled={uploading} />
                                </label>
                            </div>

                            {/* Grid */}
                            <div style={{ padding: "1.5rem", display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: "1rem", alignContent: "start" }}>
                                {loading ? (
                                    <div style={{ gridColumn: "1/-1", display: "flex", justifyContent: "center", padding: "4rem" }}><Loader2 size={40} className="animate-spin" color="#2563eb" /></div>
                                ) : filteredMedia.length === 0 ? (
                                    <div style={{ gridColumn: "1/-1", textAlign: "center", padding: "4rem", color: "#94a3b8" }}>
                                        <ImageIcon size={48} style={{ margin: "0 auto 1rem", opacity: 0.2 }} />
                                        <p style={{ fontWeight: 700 }}>Galerie vide.</p>
                                    </div>
                                ) : filteredMedia.map(m => (
                                    <div key={m.id} onClick={() => setSelectedId(m.id)}
                                        style={{ position: "relative", aspectRatio: "1", borderRadius: "1rem", overflow: "hidden", cursor: "pointer", outline: selectedId === m.id ? "3px solid #2563eb" : "none", outlineOffset: "2px", transition: "all 0.2s" }}>
                                        <Image src={m.url} alt={m.name} fill style={{ objectFit: "cover" }} />
                                        <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.1)", opacity: 0, transition: "opacity 0.2s" }} onMouseEnter={e => e.currentTarget.style.opacity = "1"} onMouseLeave={e => e.currentTarget.style.opacity = "0"}>
                                            <button onClick={(e) => handleDelete(e, m.id)} style={{ position: "absolute", top: "0.5rem", right: "0.5rem", width: "28px", height: "28px", borderRadius: "50%", background: "rgba(239,68,68,0.9)", color: "#fff", border: "none", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Trash2 size={14} /></button>
                                        </div>
                                        {selectedId === m.id && <div style={{ position: "absolute", bottom: "0.5rem", right: "0.5rem", width: "24px", height: "24px", borderRadius: "50%", background: "#2563eb", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}><Check size={14} /></div>}
                                    </div>
                                ))}
                            </div>
                        </>
                    ) : (
                        <div style={{ padding: "3rem 1.5rem", display: "flex", flexDirection: "column", alignItems: "center", gap: "1.5rem" }}>
                            <div style={{ width: 60, height: 60, borderRadius: "1.5rem", background: "rgba(37,99,235,0.1)", color: "#2563eb", display: "flex", alignItems: "center", justifyContent: "center" }}><ImageIcon size={30} /></div>
                            <div style={{ textAlign: "center", maxWidth: "400px" }}>
                                <h3 style={{ fontFamily: "Outfit", fontSize: "1.1rem", fontWeight: 900, marginBottom: "0.5rem" }}>Utiliser un lien externe</h3>
                                <p style={{ color: "#64748b", fontSize: "0.85rem", lineHeight: 1.5 }}>Collez l'URL directe d'une image (Unsplash, Imgur, Google Drive share link, etc.).</p>
                            </div>
                            <div style={{ width: "100%", maxWidth: "450px" }}>
                                <label style={{ display: "block", marginBottom: "0.5rem", fontSize: "0.7rem", fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.08em", color: "#64748b" }}>URL de l'image (Ex: Google Drive Link)</label>
                                <input type="text" value={externalUrl} onChange={e => setExternalUrl(e.target.value)} placeholder="https://exemple.com/image.jpg"
                                    style={{ width: "100%", padding: "0.85rem 1rem", border: "2px solid #e2e8f0", borderRadius: "1rem", background: "#f8fafc", color: "#0f172a", fontSize: "0.9rem", outline: "none" }} />
                            </div>
                            {externalUrl && (
                                <div style={{ position: "relative", width: 120, height: 120, borderRadius: "1.25rem", overflow: "hidden", border: "1px solid #e2e8f0" }}>
                                    <Image src={getDirectDriveLink(externalUrl)} alt="Preview" fill style={{ objectFit: "cover" }} onError={(e) => { (e.target as any).src = ""; }} />
                                    <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, padding: "2px", background: "rgba(34,197,94,0.9)", color: "#fff", fontSize: "0.55rem", fontWeight: 800, textAlign: "center" }}>APERÇU OK</div>
                                </div>
                            )}
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div style={{ padding: "1rem 1.5rem", borderTop: "1px solid #f1f5f9", background: "#f8fafc", display: "flex", justifyContent: "flex-end", gap: "0.75rem" }}>
                    <button onClick={onClose} style={{ padding: "0.6rem 1.25rem", borderRadius: "0.75rem", border: "1.5px solid #e2e8f0", background: "#fff", fontWeight: 800, color: "#64748b", cursor: "pointer", fontSize: "0.85rem" }}>Annuler</button>
                    <button disabled={tab === "gallery" ? !selectedId : !externalUrl} onClick={handleConfirm} style={{ padding: "0.6rem 2rem", borderRadius: "0.75rem", border: "none", background: (tab === "gallery" ? selectedId : externalUrl) ? "#2563eb" : "#cbd5e1", color: "#fff", fontWeight: 900, cursor: "pointer", fontSize: "0.85rem", boxShadow: (tab === "gallery" ? selectedId : externalUrl) ? "0 4px 12px rgba(37,99,235,0.2)" : "none" }}>Confirmer</button>
                </div>
            </div>
        </div>
    );
}
