import React, { useState, useEffect, useMemo } 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';

const ThemeProvider = ({ children }) => {
  const [darkMode, toggleDarkMode, setDarkMode] = useDarkMode();
  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',
    }
  };
  
  // Set initial dark mode from branding settings
  useEffect(() => {
    if (brandingSettings && localStorage.getItem("darkMode") === null) {
      const shouldUseDarkMode = brandingSettings.default_mode === 'dark';
      if (shouldUseDarkMode !== darkMode) {
        setDarkMode(shouldUseDarkMode);
      }
    }
  }, [brandingSettings]); // Remove darkMode and setDarkMode from dependencies

  // Create theme based on current settings
  const theme = useMemo(() => {
    const mode = darkMode ? 'dark' : 'light';
    const colors = {
      primary: darkMode 
        ? (brandingSettings?.dark_primary_color || defaultColors.dark.primary) 
        : (brandingSettings?.light_primary_color || defaultColors.light.primary),
      secondary: darkMode 
        ? (brandingSettings?.dark_secondary_color || defaultColors.dark.secondary) 
        : (brandingSettings?.light_secondary_color || defaultColors.light.secondary),
      background: darkMode 
        ? (brandingSettings?.dark_background_color || defaultColors.dark.background) 
        : (brandingSettings?.light_background_color || defaultColors.light.background),
      paper: darkMode 
        ? (brandingSettings?.dark_surface_color || defaultColors.dark.paper) 
        : (brandingSettings?.light_surface_color || defaultColors.light.paper),
      text: darkMode 
        ? (brandingSettings?.dark_text_color || defaultColors.dark.text) 
        : (brandingSettings?.light_text_color || defaultColors.light.text)
    };
    
    return 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: darkMode 
            ? 'rgba(255, 255, 255, 0.7)' 
            : 'rgba(0, 0, 0, 0.6)',
        },
      },
      typography: {
        fontFamily: [
          'Roboto',
          '-apple-system',
          'BlinkMacSystemFont',
          '"Segoe UI"',
          'Arial',
          'sans-serif',
        ].join(','),
      },
      components: {
        MuiButton: {
          styleOverrides: {
            root: {
              borderRadius: 6,
              textTransform: 'none',
            },
          },
        },
        MuiCard: {
          styleOverrides: {
            root: {
              borderRadius: 8,
              boxShadow: darkMode 
                ? '0 4px 20px rgba(0, 0, 0, 0.5)'
                : '0 4px 20px rgba(0, 0, 0, 0.1)',
            },
          },
        },
        MuiAppBar: {
          styleOverrides: {
            root: {
              boxShadow: darkMode 
                ? '0 4px 20px rgba(0, 0, 0, 0.5)'
                : '0 2px 10px rgba(0, 0, 0, 0.05)',
            },
          },
        },
      },
    });
  }, [darkMode, brandingSettings, defaultColors]);
  
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      {children}
    </MuiThemeProvider>
  );
};

export default ThemeProvider;