"use client";

import React, { createContext, useContext, useState, useEffect } from "react";
import { toast } from "@/components/ui/Toaster";
import { DEFAULT_VISUAL_CONFIG, type VisualConfig } from "@/lib/themeConfig";

interface ThemeContextType {
  config: VisualConfig;
  updateConfig: (field: keyof VisualConfig, value: any) => void;
  saveConfig: () => Promise<void>;
  resetConfig: () => void;
  isOpen: boolean;
  setIsOpen: (val: boolean) => void;
  saving: boolean;
}

const ThemeContext = createContext<ThemeContextType | null>(null);

export function ThemeCustomizerProvider({ children, initialConfig }: { children: React.ReactNode; initialConfig?: VisualConfig }) {
  const [config, setConfig] = useState<VisualConfig>(initialConfig || DEFAULT_VISUAL_CONFIG);
  const [isOpen, setIsOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetch("/api/ads?placement=theme_config")
      .then(res => res.json())
      .then(data => {
        if (data && typeof data === "object") {
          setConfig(prev => ({ ...prev, ...data }));
        }
      })
      .catch(() => {});
  }, []);

  // Inject CSS Variables dynamically into document root for instant live preview across the whole site
  useEffect(() => {
    if (typeof document !== "undefined") {
      const root = document.documentElement;
      // 1. Header & Logo
      root.style.setProperty("--custom-telegram-height", `${config.telegramHeight ?? 34}px`);
      root.style.setProperty("--custom-telegram-font", `${config.telegramFontSize ?? 13}px`);
      root.style.setProperty("--custom-navbar-height", `${config.navbarHeight ?? 60}px`);
      root.style.setProperty("--custom-logo-font-size", `${config.logoFontSize ?? 24}px`);
      root.style.setProperty("--custom-search-width", `${config.searchWidth ?? 480}px`);
      root.style.setProperty("--custom-header-btn-height", `${config.headerBtnHeight ?? 38}px`);
      root.style.setProperty("--custom-header-btn-radius", `${config.headerBtnRadius ?? 9999}px`);

      // 2. Sidebar & Layout
      root.style.setProperty("--custom-sidebar-width", `${config.sidebarWidth ?? 220}px`);
      root.style.setProperty("--custom-main-pl", `${config.mainPaddingLeft ?? 240}px`);
      root.style.setProperty("--custom-sidebar-top", `${config.sidebarTop ?? 105}px`);
      root.style.setProperty("--custom-sidebar-font", `${config.sidebarFontSize ?? 14}px`);
      root.style.setProperty("--custom-sidebar-item-height", `${config.sidebarItemHeight ?? 44}px`);
      root.style.setProperty("--custom-sidebar-item-radius", `${config.sidebarItemRadius ?? 12}px`);

      // 3. Les 3 Pancartes Hero
      root.style.setProperty("--custom-hero-pl", `${config.heroPaddingLeft ?? 12}px`);
      root.style.setProperty("--custom-hero-gap", `${config.heroGap ?? 14}px`);
      root.style.setProperty("--custom-hero-height", `${config.heroHeight ?? 150}px`);
      root.style.setProperty("--custom-hero-radius", `${config.heroRadius ?? 16}px`);
      root.style.setProperty("--custom-hero-title-size", `${config.heroTitleSize ?? 14}px`);
      root.style.setProperty("--custom-hero-subtitle-size", `${config.heroSubtitleSize ?? 11.5}px`);

      // 4. Catégories
      root.style.setProperty("--custom-cat-height", `${config.categoryHeight ?? 44}px`);
      root.style.setProperty("--custom-cat-font", `${config.categoryFontSize ?? 14.5}px`);
      root.style.setProperty("--custom-cat-radius", `${config.categoryRadius ?? 16}px`);
      root.style.setProperty("--custom-cat-gap", `${config.categoryGap ?? 12}px`);

      // 5. Titres de sections
      root.style.setProperty("--custom-section-title-size", `${config.sectionTitleSize ?? 22}px`);
      root.style.setProperty("--custom-section-spacing", `${config.sectionSpacing ?? 32}px`);

      // 6. Grille des Vidéos
      root.style.setProperty("--custom-video-gap", `${config.videoGap ?? 18}px`);
      root.style.setProperty("--custom-video-radius", `${config.videoRadius ?? 18}px`);
      root.style.setProperty("--custom-video-title-size", `${config.videoTitleSize ?? 13}px`);
      root.style.setProperty("--custom-video-meta-size", `${config.videoMetaSize ?? 11}px`);

      // 7. Footer
      root.style.setProperty("--custom-footer-py", `${config.footerPaddingY ?? 56}px`);
      root.style.setProperty("--custom-footer-font", `${config.footerFontSize ?? 14}px`);
      root.style.setProperty("--custom-footer-title-size", `${config.footerTitleSize ?? 12}px`);
    }
  }, [config]);

  const updateConfig = (field: keyof VisualConfig, value: any) => {
    setConfig(prev => ({ ...prev, [field]: value }));
  };

  const saveConfig = async () => {
    setSaving(true);
    try {
      const res = await fetch("/api/admin/ads", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ config }),
      });
      const data = await res.json();
      if (res.ok && data?.success) {
        toast("Configuration visuelle enregistrée avec succès !", "success");
      } else {
        toast(data?.error || "Erreur de sauvegarde", "error");
      }
    } catch (e: any) {
      toast("Erreur réseau: " + e.message, "error");
    } finally {
      setSaving(false);
    }
  };

  const resetConfig = () => {
    setConfig(DEFAULT_VISUAL_CONFIG);
    toast("Disposition réinitialisée aux valeurs par défaut", "info");
  };

  return (
    <ThemeContext.Provider value={{ config, updateConfig, saveConfig, resetConfig, isOpen, setIsOpen, saving }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useThemeCustomizer() {
  const ctx = useContext(ThemeContext);
  if (!ctx) {
    return {
      config: DEFAULT_VISUAL_CONFIG,
      updateConfig: () => {},
      saveConfig: async () => {},
      resetConfig: () => {},
      isOpen: false,
      setIsOpen: () => {},
      saving: false
    };
  }
  return ctx;
}
