/**
 * @ai-summary Theme context for managing light/dark mode across the app
 * Supports: localStorage persistence, backend sync, defaults to light theme
 * Applies Tailwind dark class to document root
 */

import { createContext, useContext, useEffect, useMemo, useState, useCallback, ReactNode, useRef } from 'react';
import { ThemeProvider as MuiThemeProvider, Theme } from '@mui/material/styles';
import { CssBaseline } from '@mui/material';
import { md3LightTheme, md3DarkTheme } from './md3Theme';

// Same storage key as useSettingsPersistence for consistency
const SETTINGS_STORAGE_KEY = 'motovaultpro-mobile-settings';

interface ThemeContextValue {
  isDarkMode: boolean;
  toggleDarkMode: () => void;
  setDarkMode: (value: boolean, syncToBackend?: boolean) => void;
  theme: Theme;
  // Callback to register backend sync function
  registerBackendSync: (syncFn: (darkMode: boolean) => void) => void;
}

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

interface ThemeProviderProps {
  children: ReactNode;
}

// Read dark mode preference from localStorage
const getStoredDarkMode = (): boolean | undefined => {
  try {
    const stored = localStorage.getItem(SETTINGS_STORAGE_KEY);
    if (stored) {
      const settings = JSON.parse(stored);
      if (settings.darkMode !== undefined && settings.darkMode !== null) {
        return settings.darkMode;
      }
    }
  } catch {
    // Ignore parse errors
  }
  return undefined;
};

// Get initial dark mode: localStorage > default to light
const getInitialDarkMode = (): boolean => {
  const stored = getStoredDarkMode();
  if (stored !== undefined) {
    return stored;
  }
  return false; // Default to light theme
};

// Update dark mode in localStorage while preserving other settings
const setStoredDarkMode = (darkMode: boolean): void => {
  try {
    const stored = localStorage.getItem(SETTINGS_STORAGE_KEY);
    const settings = stored ? JSON.parse(stored) : {};
    settings.darkMode = darkMode;
    localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(settings));
  } catch {
    // Ignore storage errors
  }
};

export const ThemeProvider = ({ children }: ThemeProviderProps) => {
  const [isDarkMode, setIsDarkMode] = useState<boolean>(getInitialDarkMode);
  const [isInitialized, setIsInitialized] = useState(false);
  const backendSyncRef = useRef<((darkMode: boolean) => void) | null>(null);

  // Initialize on mount
  useEffect(() => {
    setIsDarkMode(getInitialDarkMode());
    setIsInitialized(true);
  }, []);

  // Apply dark class to document root for Tailwind
  useEffect(() => {
    const root = document.documentElement;
    if (isDarkMode) {
      root.classList.add('dark');
    } else {
      root.classList.remove('dark');
    }
  }, [isDarkMode]);

  // Listen for storage changes from other tabs/components
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === SETTINGS_STORAGE_KEY && e.newValue) {
        try {
          const settings = JSON.parse(e.newValue);
          if (typeof settings.darkMode === 'boolean') {
            setIsDarkMode(settings.darkMode);
          }
        } catch {
          // Ignore parse errors
        }
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  // Register backend sync function (called by useThemeSync hook)
  const registerBackendSync = useCallback((syncFn: (darkMode: boolean) => void) => {
    backendSyncRef.current = syncFn;
  }, []);

  const setDarkMode = useCallback((value: boolean, syncToBackend = true) => {
    setIsDarkMode(value);
    setStoredDarkMode(value);

    // Sync to backend if registered and requested
    if (syncToBackend && backendSyncRef.current) {
      backendSyncRef.current(value);
    }
  }, []);

  const toggleDarkMode = useCallback(() => {
    setDarkMode(!isDarkMode, true);
  }, [isDarkMode, setDarkMode]);

  const theme = useMemo(() => {
    return isDarkMode ? md3DarkTheme : md3LightTheme;
  }, [isDarkMode]);

  const value = useMemo(
    () => ({
      isDarkMode,
      toggleDarkMode,
      setDarkMode,
      theme,
      registerBackendSync,
    }),
    [isDarkMode, toggleDarkMode, setDarkMode, theme, registerBackendSync]
  );

  // Prevent flash of wrong theme during SSR/initial load
  if (!isInitialized) {
    return null;
  }

  return (
    <ThemeContext.Provider value={value}>
      <MuiThemeProvider theme={theme}>
        <CssBaseline />
        {children}
      </MuiThemeProvider>
    </ThemeContext.Provider>
  );
};

export const useTheme = (): ThemeContextValue => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

// Re-export for convenience
export { md3LightTheme, md3DarkTheme } from './md3Theme';
