/**
 * Fogbreak Theme Provider
 * White-label theming from tenant config.
 * Multi-brand system with tenant-configurable branding.
 */

import React, { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { getTenantConfig, TenantConfig } from '../services/api';
import { getCachedData, cacheData, CacheKeys } from '../services/offline';

export interface Theme {
  colors: {
    primary: string;
    accent: string;
    background: string;
    surface: string;
    text: string;
    textSecondary: string;
    border: string;
    success: string;
    warning: string;
    error: string;
    info: string;
    white: string;
    card: string;
    inputBg: string;
  };
  typography: {
    headingFamily: string;
    bodyFamily: string;
  };
  spacing: {
    xs: number;
    sm: number;
    md: number;
    lg: number;
    xl: number;
    xxl: number;
  };
  borderRadius: {
    sm: number;
    md: number;
    lg: number;
    full: number;
  };
  shadow: {
    sm: {
      shadowColor: string;
      shadowOffset: { width: number; height: number };
      shadowOpacity: number;
      shadowRadius: number;
      elevation: number;
    };
    md: {
      shadowColor: string;
      shadowOffset: { width: number; height: number };
      shadowOpacity: number;
      shadowRadius: number;
      elevation: number;
    };
  };
  tenant: TenantConfig | null;
}

// Default theme (tenant-configurable brand)
const defaultTheme: Theme = {
  colors: {
    primary: '#1A3347',
    accent: '#A8875B',
    background: '#F4F1EC',
    surface: '#FFFFFF',
    text: '#1C1C1C',
    textSecondary: '#6B7280',
    border: '#E5E7EB',
    success: '#10B981',
    warning: '#F59E0B',
    error: '#EF4444',
    info: '#3B82F6',
    white: '#FFFFFF',
    card: '#FFFFFF',
    inputBg: '#F9FAFB',
  },
  typography: {
    headingFamily: 'System',
    bodyFamily: 'System',
  },
  spacing: {
    xs: 4,
    sm: 8,
    md: 16,
    lg: 24,
    xl: 32,
    xxl: 48,
  },
  borderRadius: {
    sm: 6,
    md: 10,
    lg: 16,
    full: 9999,
  },
  shadow: {
    sm: {
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 1 },
      shadowOpacity: 0.05,
      shadowRadius: 2,
      elevation: 1,
    },
    md: {
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.1,
      shadowRadius: 4,
      elevation: 3,
    },
  },
  tenant: null,
};

interface ThemeContextValue {
  theme: Theme;
  isLoading: boolean;
  refreshTheme: () => Promise<void>;
}

const ThemeContext = createContext<ThemeContextValue>({
  theme: defaultTheme,
  isLoading: true,
  refreshTheme: async () => {},
});

export function useTheme(): ThemeContextValue {
  return useContext(ThemeContext);
}

function buildThemeFromConfig(config: TenantConfig): Theme {
  return {
    ...defaultTheme,
    colors: {
      ...defaultTheme.colors,
      primary: config.primary_color || defaultTheme.colors.primary,
      accent: config.accent_color || defaultTheme.colors.accent,
      background: config.bg_color || defaultTheme.colors.background,
      text: config.text_color || defaultTheme.colors.text,
    },
    typography: {
      headingFamily: config.typography_heading || defaultTheme.typography.headingFamily,
      bodyFamily: config.typography_body || defaultTheme.typography.bodyFamily,
    },
    tenant: config,
  };
}

interface ThemeProviderProps {
  children: ReactNode;
}

export default function ThemeProvider({ children }: ThemeProviderProps) {
  const [theme, setTheme] = useState<Theme>(defaultTheme);
  const [isLoading, setIsLoading] = useState(true);

  const refreshTheme = async () => {
    try {
      // Try cache first
      const cached = await getCachedData<TenantConfig>(CacheKeys.TENANT_CONFIG);
      if (cached) {
        setTheme(buildThemeFromConfig(cached));
      }

      // Then fetch fresh
      const response = await getTenantConfig();
      if (response.success && response.data) {
        setTheme(buildThemeFromConfig(response.data));
        await cacheData(CacheKeys.TENANT_CONFIG, response.data, 24 * 60 * 60 * 1000);
      }
    } catch {
      // Keep default theme
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    refreshTheme();
  }, []);

  return (
    <ThemeContext.Provider value={{ theme, isLoading, refreshTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}
