import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';

interface ThemeColors {
  primary: string;
  secondary: string;
  accent: string;
  background?: string;
  text?: string;
}

interface ThemeTypography {
  preset: 'professional' | 'modern' | 'elegant' | 'tech' | 'custom';
  customFonts?: {
    heading: string;
    body: string;
  };
  scale?: number;
}

interface ThemeConfig {
  mode: 'disabled' | 'full' | 'checkout_only';
  layout: 'classic' | 'modern' | 'boutique' | 'launch';
  colors: ThemeColors;
  typography: ThemeTypography;
}

interface ThemeContextValue {
  config: ThemeConfig;
  isFullSPA: boolean;
  isCheckoutOnly: boolean;
  isLaunchLayout: boolean;
  colorMode: 'light' | 'dark';
  setColorMode: (mode: 'light' | 'dark') => void;
  toggleColorMode: () => void;
  loading: boolean;
}

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

// Map our predefined font pairs to presets
const FONT_PAIR_MAP: Record<string, string> = {
  modern: 'modern',
  editorial: 'elegant',
  friendly: 'professional',
  elegant: 'elegant',
};

const TYPOGRAPHY_PRESETS = {
  modern: {
    heading: "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    body: "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    headingWeight: 700,
    bodyWeight: 400,
  },
  professional: {
    heading: "'Poppins', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    body: "'Open Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    headingWeight: 600,
    bodyWeight: 400,
  },
  elegant: {
    heading: "'Playfair Display', Georgia, serif",
    body: "'Source Sans 3', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    headingWeight: 700,
    bodyWeight: 400,
  },
  tech: {
    heading: "'Cormorant Garamond', Georgia, serif",
    body: "'Lato', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    headingWeight: 700,
    bodyWeight: 400,
  },
};

export function ThemeProvider({
  config: initialConfig,
  children
}: {
  config: ThemeConfig;
  children: ReactNode;
}) {
  const [config, setConfig] = useState<ThemeConfig>(initialConfig);
  const [colorMode, setColorModeState] = useState<'light' | 'dark'>(() => {
    if (typeof window === 'undefined') return 'light';
    const stored = window.localStorage.getItem('woonoow_customer_theme');
    if (stored === 'light' || stored === 'dark') return stored;
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  });
  const [loading, setLoading] = useState(true);

  // Fetch settings from API
  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const apiRoot = (window as any).woonoowCustomer?.apiRoot || '/wp-json/woonoow/v1';
        const response = await fetch(`${apiRoot}/appearance/settings`, {
          credentials: 'include',
        });

        if (response.ok) {
          const data = await response.json();
          const settings = data.data;

          if (settings?.general) {
            const general = settings.general;

            // Map API settings to theme config
            const mappedPreset = FONT_PAIR_MAP[general.typography?.predefined_pair] || 'modern';
            const newConfig: ThemeConfig = {
              mode: general.spa_mode || 'full',
              layout: 'modern', // Keep existing layout for now
              colors: {
                primary: general.colors?.primary || '#3B82F6',
                secondary: general.colors?.secondary || '#8B5CF6',
                accent: general.colors?.accent || '#10B981',
                background: general.colors?.background || '#ffffff',
                text: general.colors?.text || '#111827',
              },
              typography: {
                preset: mappedPreset as 'professional' | 'modern' | 'elegant' | 'tech' | 'custom',
                scale: general.typography?.scale || 1.0,
              },
            };

            setConfig(newConfig);
          }
        }
      } catch (error) {
        console.error('Failed to fetch appearance settings:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchSettings();
  }, []);

  useEffect(() => {
    const handleLocationChange = () => {
      const root = document.documentElement;

      // Inject color CSS variables
      root.style.setProperty('--color-primary', config.colors.primary);
      root.style.setProperty('--color-secondary', config.colors.secondary);
      root.style.setProperty('--color-accent', config.colors.accent);

      if (config.colors.background) {
        root.style.setProperty('--color-background', config.colors.background);
      }
      if (config.colors.text) {
        root.style.setProperty('--color-text', config.colors.text);
      }

      // Inject typography CSS variables
      const typoPreset = TYPOGRAPHY_PRESETS[config.typography.preset as keyof typeof TYPOGRAPHY_PRESETS];
      if (typoPreset) {
        root.style.setProperty('--font-heading', typoPreset.heading);
        root.style.setProperty('--font-body', typoPreset.body);
        root.style.setProperty('--font-weight-heading', typoPreset.headingWeight.toString());
        root.style.setProperty('--font-weight-body', typoPreset.bodyWeight.toString());
      }

      // Apply font scale
      if (config.typography.scale) {
        root.style.setProperty('--font-scale', config.typography.scale.toString());
      }

      // We're using self-hosted fonts now, no need to load from Google
      // loadTypography(config.typography.preset, config.typography.customFonts);

      // Add layout class to body
      document.body.classList.remove('layout-classic', 'layout-modern', 'layout-boutique', 'layout-launch');
      document.body.classList.add(`layout-${config.layout}`);

      // Add mode class to body
      document.body.classList.remove('mode-disabled', 'mode-full', 'mode-checkout-only');
      document.body.classList.add(`mode-${config.mode}`);
    };

    handleLocationChange();
  }, [config]);

  useEffect(() => {
    const root = document.documentElement;

    root.classList.remove('light', 'dark');
    root.classList.add(colorMode);
    root.style.colorScheme = colorMode;

    if (colorMode === 'dark') {
      root.style.setProperty('--color-background', '#020817');
      root.style.setProperty('--color-text', '#F8FAFC');
      root.style.setProperty('--wn-background', '#020817');
      root.style.setProperty('--wn-text', '#F8FAFC');
      return;
    }

    root.style.setProperty('--color-background', config.colors.background || '#ffffff');
    root.style.setProperty('--color-text', config.colors.text || '#111827');
    root.style.setProperty('--wn-background', config.colors.background || '#ffffff');
    root.style.setProperty('--wn-text', config.colors.text || '#111827');
  }, [colorMode, config.colors.background, config.colors.text]);

  const setColorMode = (mode: 'light' | 'dark') => {
    window.localStorage.setItem('woonoow_customer_theme', mode);
    setColorModeState(mode);
  };

  const toggleColorMode = () => {
    setColorMode(colorMode === 'dark' ? 'light' : 'dark');
  };

  const contextValue: ThemeContextValue = {
    config,
    isFullSPA: config.mode === 'full',
    isCheckoutOnly: config.mode === 'checkout_only',
    isLaunchLayout: config.layout === 'launch',
    colorMode,
    setColorMode,
    toggleColorMode,
    loading,
  };

  return (
    <ThemeContext.Provider value={contextValue}>
      {children}
    </ThemeContext.Provider>
  );
}

/**
 * Hook to access theme configuration
 */
export function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}
