"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useThemeCustomizer } from "@/components/ThemeCustomizerContext";
import { 
  Sliders, 
  Save, 
  RotateCcw, 
  X, 
  Sparkles, 
  Layout, 
  Move, 
  Search, 
  Folder, 
  Type, 
  Video, 
  Layers,
  PanelBottom,
  CheckCircle2
} from "lucide-react";

export function LiveVisualCustomizer() {
  const { data: session } = useSession();
  const { config, updateConfig, saveConfig, resetConfig, isOpen, setIsOpen, saving } = useThemeCustomizer();
  const [activeTab, setActiveTab] = useState<"layout" | "header" | "hero" | "categories" | "sections" | "videos" | "footer">("layout");
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

  const role = (session?.user as any)?.role;
  const isAdmin = ["ADMIN", "SUPERADMIN", "MODERATOR", "EDITOR"].includes(role);

  useEffect(() => {
    const handleOpen = () => setIsOpen(true);
    window.addEventListener("open-visual-customizer", handleOpen);
    return () => window.removeEventListener("open-visual-customizer", handleOpen);
  }, [setIsOpen]);

  const handleUpdate = (field: any, val: any) => {
    updateConfig(field, val);
    setHasUnsavedChanges(true);
  };

  const handleSave = async () => {
    await saveConfig();
    setHasUnsavedChanges(false);
  };

  if (!isAdmin) return null;

  return (
    <>
      {/* 📌 BOUTON FLOTTANT EN BAS À DROITE POUR OUVRIR LE CUSTOMIZER (Visible sur Desktop uniquement pour ne pas cacher le menu mobile) */}
      {!isOpen && (
        <button
          onClick={() => setIsOpen(true)}
          className="hidden md:flex fixed bottom-6 right-6 z-[9999] items-center gap-2 px-4 py-2.5 rounded-full bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white font-black text-xs shadow-[0_0_25px_rgba(224,90,104,0.6)] hover:scale-105 active:scale-95 transition-all cursor-pointer border border-white/30"
          title="Ouvrir l'éditeur visuel en direct"
        >
          <Sliders size={15} />
          <span>🎨 Modifier le Site</span>
        </button>
      )}

      {/* 📌 BARRE FLOTTANTE D'ALERTE EN BAS SI MODIFICATIONS NON ENREGISTRÉES */}
      {hasUnsavedChanges && !isOpen && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[9999] flex items-center gap-3 px-5 py-3 rounded-2xl bg-[#12080b]/95 border border-emerald-500/60 backdrop-blur-2xl shadow-[0_0_30px_rgba(16,185,129,0.4)] animate-bounce">
          <span className="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-ping" />
          <span className="text-xs font-bold text-white">Modifications en attente</span>
          <button
            onClick={handleSave}
            disabled={saving}
            className="px-3.5 py-1.5 rounded-xl bg-emerald-500 hover:bg-emerald-400 text-black font-black text-xs flex items-center gap-1.5 shadow-lg active:scale-95 transition-all cursor-pointer"
          >
            <Save size={13} />
            <span>{saving ? "Sauvegarde..." : "💾 Enregistrer"}</span>
          </button>
        </div>
      )}

      {/* 📌 PANNEAU CONTRÔLEUR VISUEL FLOTTANT (DESIGN PINNÉ FIXE) */}
      {isOpen && (
        <div className="fixed top-3 right-3 sm:right-6 z-[99999] w-[400px] h-[92vh] max-h-[850px] bg-[#12080b]/98 border border-[#2e1217] backdrop-blur-3xl rounded-3xl p-5 shadow-[0_0_50px_rgba(0,0,0,0.9)] flex flex-col justify-between text-white animate-fade-in select-none">
          
          {/* 1. Header Pinned (Fixe en haut avec bouton Save immédiat) */}
          <div className="shrink-0 pb-3 border-b border-white/10 mb-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Sparkles className="text-[#e05a68]" size={18} />
                <div>
                  <h3 className="font-black text-sm text-white">Éditeur Visuel Live</h3>
                  <p className="text-[10px] text-[#a38890]">Ajuste tous les éléments du site en direct</p>
                </div>
              </div>

              <div className="flex items-center gap-2">
                {/* 💾 BOUTON ENREGISTRER RAPIDE DANS LE HEADER */}
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className="px-3 py-1.5 rounded-xl bg-gradient-to-r from-emerald-500 to-teal-400 hover:from-emerald-400 hover:to-teal-300 text-black font-black text-xs flex items-center gap-1.5 shadow-[0_0_15px_rgba(16,185,129,0.4)] active:scale-95 transition-all cursor-pointer"
                  title="Enregistrer définitivement les modifications"
                >
                  <Save size={13} />
                  <span>{saving ? "..." : "Enregistrer"}</span>
                </button>

                <button
                  onClick={() => setIsOpen(false)}
                  className="w-7 h-7 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white/70 hover:text-white transition-colors cursor-pointer"
                  title="Fermer"
                >
                  <X size={15} />
                </button>
              </div>
            </div>

            {/* Onglets rapides */}
            <div className="grid grid-cols-4 gap-1 mt-3 p-1 bg-black/40 rounded-xl border border-white/5 text-[10px] font-bold">
              {[
                { id: "layout", label: "Sidebar", icon: Layout },
                { id: "header", label: "Header/Logo", icon: Search },
                { id: "hero", label: "3 Pancartes", icon: Move },
                { id: "categories", label: "Catégories", icon: Folder },
                { id: "sections", label: "Titres", icon: Type },
                { id: "videos", label: "Vidéos", icon: Video },
                { id: "footer", label: "Footer", icon: PanelBottom },
              ].map(tab => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as any)}
                  className={`py-1.5 px-1 rounded-lg flex items-center justify-center gap-1 transition-all cursor-pointer ${
                    activeTab === tab.id
                      ? "bg-[#e05a68] text-black font-black shadow-md"
                      : "text-[#a38890] hover:bg-white/5 hover:text-white"
                  }`}
                >
                  <span className="truncate">{tab.label}</span>
                </button>
              ))}
            </div>
          </div>

          {/* 2. Controls Content (Zone de réglages défilable) */}
          <div className="flex-1 overflow-y-auto pr-1 space-y-4 custom-scrollbar">
            
            {/* TAB 1: SIDEBAR & LAYOUT */}
            {activeTab === "layout" && (
              <div className="space-y-4">
                <h4 className="text-xs font-black text-[#e05a68] uppercase tracking-wider">Navigation Latérale</h4>
                
                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Largeur de la Sidebar</span>
                    <span className="font-mono text-white">{config.sidebarWidth ?? 220}px</span>
                  </div>
                  <input
                    type="range"
                    min="160"
                    max="300"
                    value={config.sidebarWidth ?? 220}
                    onChange={(e) => handleUpdate("sidebarWidth", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Marge gauche du contenu principal</span>
                    <span className="font-mono text-white">{config.mainPaddingLeft ?? 240}px</span>
                  </div>
                  <input
                    type="range"
                    min="180"
                    max="340"
                    value={config.mainPaddingLeft ?? 240}
                    onChange={(e) => handleUpdate("mainPaddingLeft", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Position haute (Top)</span>
                    <span className="font-mono text-white">{config.sidebarTop ?? 105}px</span>
                  </div>
                  <input
                    type="range"
                    min="60"
                    max="150"
                    value={config.sidebarTop ?? 105}
                    onChange={(e) => handleUpdate("sidebarTop", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Taille de police des liens</span>
                    <span className="font-mono text-white">{config.sidebarFontSize ?? 14}px</span>
                  </div>
                  <input
                    type="range"
                    min="11"
                    max="18"
                    value={config.sidebarFontSize ?? 14}
                    onChange={(e) => handleUpdate("sidebarFontSize", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Hauteur des boutons de menu</span>
                    <span className="font-mono text-white">{config.sidebarItemHeight ?? 44}px</span>
                  </div>
                  <input
                    type="range"
                    min="32"
                    max="56"
                    value={config.sidebarItemHeight ?? 44}
                    onChange={(e) => handleUpdate("sidebarItemHeight", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>
              </div>
            )}

            {/* TAB 2: HEADER & LOGO */}
            {activeTab === "header" && (
              <div className="space-y-4">
                <h4 className="text-xs font-black text-[#e05a68] uppercase tracking-wider">Barre du Haut & Recherche</h4>
                
                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Taille du Logo MTBR</span>
                    <span className="font-mono text-white">{config.logoFontSize ?? 24}px</span>
                  </div>
                  <input
                    type="range"
                    min="16"
                    max="36"
                    value={config.logoFontSize ?? 24}
                    onChange={(e) => handleUpdate("logoFontSize", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Hauteur de la Barre Header</span>
                    <span className="font-mono text-white">{config.navbarHeight ?? 60}px</span>
                  </div>
                  <input
                    type="range"
                    min="48"
                    max="80"
                    value={config.navbarHeight ?? 60}
                    onChange={(e) => handleUpdate("navbarHeight", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Largeur de la Barre de Recherche</span>
                    <span className="font-mono text-white">{config.searchWidth ?? 480}px</span>
                  </div>
                  <input
                    type="range"
                    min="250"
                    max="700"
                    value={config.searchWidth ?? 480}
                    onChange={(e) => handleUpdate("searchWidth", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Hauteur du Bandeau Telegram</span>
                    <span className="font-mono text-white">{config.telegramHeight ?? 34}px</span>
                  </div>
                  <input
                    type="range"
                    min="24"
                    max="50"
                    value={config.telegramHeight ?? 34}
                    onChange={(e) => handleUpdate("telegramHeight", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>
              </div>
            )}

            {/* TAB 3: LES 3 PANCARTES HERO */}
            {activeTab === "hero" && (
              <div className="space-y-4">
                <h4 className="text-xs font-black text-[#e05a68] uppercase tracking-wider">Les 3 Pancartes d'Accueil</h4>
                
                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Marge gauche des 3 pancartes</span>
                    <span className="font-mono text-white">{config.heroPaddingLeft ?? 12}px</span>
                  </div>
                  <input
                    type="range"
                    min="0"
                    max="60"
                    value={config.heroPaddingLeft ?? 12}
                    onChange={(e) => handleUpdate("heroPaddingLeft", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Espacement entre les pancartes</span>
                    <span className="font-mono text-white">{config.heroGap ?? 14}px</span>
                  </div>
                  <input
                    type="range"
                    min="6"
                    max="30"
                    value={config.heroGap ?? 14}
                    onChange={(e) => handleUpdate("heroGap", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Hauteur des pancartes</span>
                    <span className="font-mono text-white">{config.heroHeight ?? 150}px</span>
                  </div>
                  <input
                    type="range"
                    min="100"
                    max="240"
                    value={config.heroHeight ?? 150}
                    onChange={(e) => handleUpdate("heroHeight", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Arrondi des coins (Radius)</span>
                    <span className="font-mono text-white">{config.heroRadius ?? 16}px</span>
                  </div>
                  <input
                    type="range"
                    min="4"
                    max="32"
                    value={config.heroRadius ?? 16}
                    onChange={(e) => handleUpdate("heroRadius", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div className="pt-2 border-t border-white/10">
                  <a
                    href="/admin/settings#pancartes"
                    className="flex items-center justify-center gap-2 w-full py-2.5 px-3 rounded-xl bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white font-black text-xs hover:opacity-90 transition-all text-center"
                  >
                    ✏️ Modifier Textes, Images & Liens des 3 Pancartes
                  </a>
                </div>
              </div>
            )}

            {/* TAB 4: CATÉGORIES */}
            {activeTab === "categories" && (
              <div className="space-y-4">
                <h4 className="text-xs font-black text-[#e05a68] uppercase tracking-wider">Pastilles des Catégories</h4>
                
                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Hauteur des pastilles</span>
                    <span className="font-mono text-white">{config.categoryHeight ?? 44}px</span>
                  </div>
                  <input
                    type="range"
                    min="28"
                    max="60"
                    value={config.categoryHeight ?? 44}
                    onChange={(e) => handleUpdate("categoryHeight", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Taille du texte des catégories</span>
                    <span className="font-mono text-white">{config.categoryFontSize ?? 14.5}px</span>
                  </div>
                  <input
                    type="range"
                    min="11"
                    max="18"
                    step="0.5"
                    value={config.categoryFontSize ?? 14.5}
                    onChange={(e) => handleUpdate("categoryFontSize", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Espacement entre les catégories</span>
                    <span className="font-mono text-white">{config.categoryGap ?? 12}px</span>
                  </div>
                  <input
                    type="range"
                    min="6"
                    max="24"
                    value={config.categoryGap ?? 12}
                    onChange={(e) => handleUpdate("categoryGap", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>
              </div>
            )}

            {/* TAB 5: TITRES DES SECTIONS */}
            {activeTab === "sections" && (
              <div className="space-y-4">
                <h4 className="text-xs font-black text-[#e05a68] uppercase tracking-wider">Titres & Espacements</h4>
                
                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Taille des titres de sections (H2)</span>
                    <span className="font-mono text-white">{config.sectionTitleSize ?? 22}px</span>
                  </div>
                  <input
                    type="range"
                    min="16"
                    max="32"
                    value={config.sectionTitleSize ?? 22}
                    onChange={(e) => handleUpdate("sectionTitleSize", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Espacement entre les sections</span>
                    <span className="font-mono text-white">{config.sectionSpacing ?? 32}px</span>
                  </div>
                  <input
                    type="range"
                    min="16"
                    max="64"
                    value={config.sectionSpacing ?? 32}
                    onChange={(e) => handleUpdate("sectionSpacing", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>
              </div>
            )}

            {/* TAB 6: GRILLE DES VIDÉOS */}
            {activeTab === "videos" && (
              <div className="space-y-4">
                <h4 className="text-xs font-black text-[#e05a68] uppercase tracking-wider">Cartes & Grille Vidéos</h4>
                
                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Espacement de la grille (Gap)</span>
                    <span className="font-mono text-white">{config.videoGap ?? 18}px</span>
                  </div>
                  <input
                    type="range"
                    min="8"
                    max="32"
                    value={config.videoGap ?? 18}
                    onChange={(e) => handleUpdate("videoGap", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Arrondi des vignettes (Radius)</span>
                    <span className="font-mono text-white">{config.videoRadius ?? 18}px</span>
                  </div>
                  <input
                    type="range"
                    min="4"
                    max="32"
                    value={config.videoRadius ?? 18}
                    onChange={(e) => handleUpdate("videoRadius", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Taille du titre de vidéo</span>
                    <span className="font-mono text-white">{config.videoTitleSize ?? 13}px</span>
                  </div>
                  <input
                    type="range"
                    min="11"
                    max="17"
                    value={config.videoTitleSize ?? 13}
                    onChange={(e) => handleUpdate("videoTitleSize", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>
              </div>
            )}

            {/* TAB 7: FOOTER */}
            {activeTab === "footer" && (
              <div className="space-y-4">
                <h4 className="text-xs font-black text-[#e05a68] uppercase tracking-wider">Pied de Page (Footer)</h4>
                
                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Padding Vertical du Footer</span>
                    <span className="font-mono text-white">{config.footerPaddingY ?? 56}px</span>
                  </div>
                  <input
                    type="range"
                    min="24"
                    max="96"
                    value={config.footerPaddingY ?? 56}
                    onChange={(e) => handleUpdate("footerPaddingY", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] font-bold text-[#a38890] mb-1">
                    <span>Taille du texte des liens</span>
                    <span className="font-mono text-white">{config.footerFontSize ?? 14}px</span>
                  </div>
                  <input
                    type="range"
                    min="10"
                    max="18"
                    value={config.footerFontSize ?? 14}
                    onChange={(e) => handleUpdate("footerFontSize", Number(e.target.value))}
                    className="w-full accent-[#e05a68] cursor-pointer"
                  />
                </div>
              </div>
            )}

          </div>

          {/* 3. Action Buttons Pinned (Fixe en bas, 100% visible quoi qu'il arrive !) */}
          <div className="shrink-0 pt-3 mt-3 border-t border-white/10 flex flex-col gap-2">
            <button
              onClick={handleSave}
              disabled={saving}
              className="w-full flex items-center justify-center gap-2 py-3 rounded-2xl bg-gradient-to-r from-emerald-500 to-teal-400 hover:from-emerald-400 hover:to-teal-300 text-black font-black text-xs hover:scale-[1.02] active:scale-95 transition-all shadow-[0_0_20px_rgba(16,185,129,0.4)] cursor-pointer disabled:opacity-50"
            >
              <Save size={15} />
              <span>{saving ? "Sauvegarde en cours..." : "💾 Sauvegarder Définitivement"}</span>
            </button>

            <button
              onClick={resetConfig}
              className="w-full flex items-center justify-center gap-2 py-2 rounded-xl bg-white/5 hover:bg-white/10 text-[#a38890] hover:text-white font-bold text-[11px] transition-all cursor-pointer active:scale-95"
            >
              <RotateCcw size={13} />
              <span>Réinitialiser par défaut</span>
            </button>
          </div>

        </div>
      )}
    </>
  );
}

