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;
  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,
  },
};

/**
 * Load Google Fonts for typography preset
 */
function loadTypography(preset: string, customFonts?: { heading: string; body: string }) {
  // Remove existing font link if any
  const existingLink = document.getElementById('woonoow-fonts');
  if (existingLink) {
    existingLink.remove();
  }
  
  if (preset === 'custom' && customFonts) {
    // TODO: Handle custom fonts
    return;
  }
  
  const fontMap: Record<string, string[]> = {
    professional: ['Inter:400,600,700', 'Lora:400,700'],
    modern: ['Poppins:400,600,700', 'Roboto:400,700'],
    elegant: ['Playfair+Display:400,700', 'Source+Sans+Pro:400,700'],
    tech: ['Space+Grotesk:400,700', 'IBM+Plex+Mono:400,700'],
  };
  
  const fonts = fontMap[preset];
  if (!fonts) return;
  
  const link = document.createElement('link');
  link.id = 'woonoow-fonts';
  link.href = `https://fonts.googleapis.com/css2?family=${fonts.join('&family=')}&display=swap`;
  link.rel = 'stylesheet';
  document.head.appendChild(link);
}

/**
 * Generate color shades from base color
 */
function generateColorShades(baseColor: string): Record<number, string> {
  // For now, just return the base color
  // TODO: Implement proper color shade generation
  return {
    50: baseColor,
    100: baseColor,
    200: baseColor,
    300: baseColor,
    400: baseColor,
    500: baseColor,
    600: baseColor,
    700: baseColor,
    800: baseColor,
    900: baseColor,
  };
}

export function ThemeProvider({ 
  config: initialConfig, 
  children 
}: { 
  config: ThemeConfig; 
  children: ReactNode;
}) {
  const [config, setConfig] = useState<ThemeConfig>(initialConfig);
  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 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}`);
  }, [config]);
  
  const contextValue: ThemeContextValue = {
    config,
    isFullSPA: config.mode === 'full',
    isCheckoutOnly: config.mode === 'checkout_only',
    isLaunchLayout: config.layout === 'launch',
    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;
}

/**
 * Hook to check if we're in a specific layout
 */
export function useLayout() {
  const { config } = useTheme();
  return {
    isClassic: config.layout === 'classic',
    isModern: config.layout === 'modern',
    isBoutique: config.layout === 'boutique',
    isLaunch: config.layout === 'launch',
    layout: config.layout,
  };
}

/**
 * Hook to check current mode
 */
export function useMode() {
  const { config, isFullSPA, isCheckoutOnly } = useTheme();
  return {
    isFullSPA,
    isCheckoutOnly,
    isDisabled: config.mode === 'disabled',
    mode: config.mode,
  };
}
