'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Theme } from '@mui/material/styles';
import { purpleTheme } from '@/styles/themes/purpleTheme';
import { highContrastTheme } from '@/styles/themes/highContrastTheme';

export type ThemeMode = 'standard' | 'highContrast';

interface ThemeContextType {
  themeMode: ThemeMode;
  toggleTheme: () => void;
  setThemeMode: (mode: ThemeMode) => void;
  currentTheme: Theme;
}

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

const THEME_STORAGE_KEY = 'maternal_theme_preference';

export function ThemeContextProvider({ children }: { children: ReactNode }) {
  const [themeMode, setThemeModeState] = useState<ThemeMode>('standard');
  const [mounted, setMounted] = useState(false);

  // Load theme preference from localStorage on mount
  useEffect(() => {
    const savedTheme = localStorage.getItem(THEME_STORAGE_KEY) as ThemeMode | null;
    if (savedTheme === 'highContrast' || savedTheme === 'standard') {
      setThemeModeState(savedTheme);
    }
    setMounted(true);
  }, []);

  // Save theme preference to localStorage when it changes
  const setThemeMode = (mode: ThemeMode) => {
    setThemeModeState(mode);
    localStorage.setItem(THEME_STORAGE_KEY, mode);
  };

  const toggleTheme = () => {
    const newMode = themeMode === 'standard' ? 'highContrast' : 'standard';
    setThemeMode(newMode);
  };

  const currentTheme = themeMode === 'highContrast' ? highContrastTheme : purpleTheme;

  // Prevent flash of wrong theme
  if (!mounted) {
    return null;
  }

  return (
    <ThemeContext.Provider value={{ themeMode, toggleTheme, setThemeMode, currentTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useThemeContext() {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useThemeContext must be used within a ThemeContextProvider');
  }
  return context;
}
