import React, { useState, useEffect } from 'react';
import { ThemeProvider as MuiThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import { createTheme } from '@mui/material/styles';
import { red, amber, grey, deepPurple } from '@mui/material/colors';
import { useQuery } from '@tanstack/react-query';
import apiClient from '@services/api';
import { useDarkMode } from '@hooks/reduxHooks';
import useBrandingSettings from '@hooks/brandingHooks';

/**
 * Custom ThemeProvider that uses branding settings for white labeling
 */
const ThemeProvider = ({ children }) => {
  const [darkMode, _, setDarkMode] = useDarkMode();
  const [theme, setTheme] = useState(null);
  
  // Fetch branding settings
  const { data: brandingSettings } = useBrandingSettings();
  
  // Default colors
  const defaultColors = {
    light: {
      primary: deepPurple[400],
      secondary: amber[500],
      error: red.A400,
      background: '#f5f5f5',
      paper: '#fff',
      text: '#000000',
    },
    dark: {
      primary: deepPurple[300],
      secondary: amber[300],
      error: red.A400,
      background: grey[900],
      paper: grey[800],
      text: '#ffffff',
    }
  };
  
  
  useEffect(() => {
    // Only pull from default if user specified style hasn't been set
    if(brandingSettings){
      let isDarkMode = darkMode;
      if(localStorage.getItem("darkMode") == null){
        isDarkMode = brandingSettings?.default_mode === 'dark' ? true : darkMode;
        setDarkMode(isDarkMode);
      }
      handleDarkMode(isDarkMode)
    }
  }, [brandingSettings, darkMode]);
  function handleDarkMode(darkMode){
    let isDarkMode = darkMode;
    
    // Get colors based on mode
    const mode = isDarkMode ? 'dark' : 'light';
    const colors = {
      primary: isDarkMode 
        ? (brandingSettings?.dark_primary_color || defaultColors.dark.primary) 
        : (brandingSettings?.light_primary_color || defaultColors.light.primary),
      secondary: isDarkMode 
        ? (brandingSettings?.dark_secondary_color || defaultColors.dark.secondary) 
        : (brandingSettings?.light_secondary_color || defaultColors.light.secondary),
      background: isDarkMode 
        ? (brandingSettings?.dark_background_color || defaultColors.dark.background) 
        : (brandingSettings?.light_background_color || defaultColors.light.background),
      paper: isDarkMode 
        ? (brandingSettings?.dark_surface_color || defaultColors.dark.paper) 
        : (brandingSettings?.light_surface_color || defaultColors.light.paper),
      text: isDarkMode 
        ? (brandingSettings?.dark_text_color || defaultColors.dark.text) 
        : (brandingSettings?.light_text_color || defaultColors.light.text)
    };
    
    // Create theme
    const newTheme = createTheme({
      palette: {
        mode,
        primary: {
          main: colors.primary,
        },
        secondary: {
          main: colors.secondary,
        },
        error: {
          main: defaultColors[mode].error,
        },
        background: {
          default: colors.background,
          paper: colors.paper,
        },
        text: {
          primary: colors.text,
          secondary: isDarkMode 
            ? 'rgba(255, 255, 255, 0.7)' 
            : 'rgba(0, 0, 0, 0.6)',
        },
      },
      typography: {
        fontFamily: [
          'Roboto',
          '-apple-system',
          'BlinkMacSystemFont',
          '"Segoe UI"',
          'Arial',
          'sans-serif',
        ].join(','),
        h1: {
          fontSize: '2.5rem',
          fontWeight: 500,
        },
        h2: {
          fontSize: '2rem',
          fontWeight: 500,
        },
        h3: {
          fontSize: '1.75rem',
          fontWeight: 500,
        },
        h4: {
          fontSize: '1.5rem',
          fontWeight: 500,
        },
        h5: {
          fontSize: '1.25rem',
          fontWeight: 500,
        },
        h6: {
          fontSize: '1rem',
          fontWeight: 500,
        },
      },
      components: {
        MuiButton: {
          styleOverrides: {
            root: {
              borderRadius: 6,
              textTransform: 'none',
            },
          },
        },
        MuiCard: {
          styleOverrides: {
            root: {
              borderRadius: 8,
              boxShadow: isDarkMode 
                ? '0 4px 20px rgba(0, 0, 0, 0.5)'
                : '0 4px 20px rgba(0, 0, 0, 0.1)',
            },
          },
        },
        MuiAppBar: {
          styleOverrides: {
            root: {
              boxShadow: isDarkMode 
                ? '0 4px 20px rgba(0, 0, 0, 0.5)'
                : '0 2px 10px rgba(0, 0, 0, 0.05)',
            },
          },
        },
      },
    });
    
    setTheme(newTheme);
  }
  // Use a default theme while loading
  if (!theme) {
    const defaultTheme = createTheme({
      palette: {
        mode: darkMode ? 'dark' : 'light',
        primary: {
          main: darkMode ? defaultColors.dark.primary : defaultColors.light.primary,
        },
        secondary: {
          main: darkMode ? defaultColors.dark.secondary : defaultColors.light.secondary,
        },
      },
    });
    
    return (
      <MuiThemeProvider theme={defaultTheme}>
        <CssBaseline />
        {children}
      </MuiThemeProvider>
    );
  }
  
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      {children}
    </MuiThemeProvider>
  );
};

export default ThemeProvider;