import { createTheme, PaletteMode, Theme } from "@mui/material";
import React, {
  createContext,
  ReactNode,
  useContext,
  useEffect,
  useState,
} from "react";

interface ThemeContextType {
  mode: PaletteMode;
  toggleColorMode: () => void;
  theme: Theme;
}

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

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

interface ThemeProviderProps {
  children: ReactNode;
}

export const CustomThemeProvider: React.FC<ThemeProviderProps> = ({
  children,
}) => {
  // Always use 'dark' for now
  const [mode, setMode] = useState<PaletteMode>("dark");

  // Save mode to localStorage whenever it changes
  useEffect(() => {
    localStorage.setItem("colorMode", mode);
  }, [mode]);

  const toggleColorMode = () => {
    setMode((prevMode) => (prevMode === "light" ? "dark" : "light"));
  };

  // Create theme based on current mode
  const theme = createTheme({
    shape: {
      borderRadius: 8,
    },
    palette: {
      mode,
      primary: {
        main: mode === "light" ? "#111827" : "#90CAF9",
      },
      secondary: {
        main: mode === "light" ? "#f8fafc" : "#00ABFF",
      },
      background: {
        default: mode === "light" ? "#ffffff" : "#1E1E1E",
        paper: mode === "light" ? "#ffffff" : "#252526",
      },
      text: {
        primary: mode === "light" ? "#111827" : "#ffffff",
        secondary: mode === "light" ? "#6b7280" : "#9ca3af",
      },
    },
    typography: {
      fontFamily:
        "system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",
    },
    components: {
      MuiButton: {
        styleOverrides: {
          root: {
            textTransform: "none",
          },
        },
      },
      MuiTypography: {
        styleOverrides: {
          root: {
            textTransform: "none",
          },
        },
      },
    },
  });

  const value = {
    mode,
    toggleColorMode,
    theme,
  };

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