"use client";

import { createContext, use, useMemo, type ReactNode } from "react";
import CssBaseline from "@mui/material/CssBaseline";
import {
  ThemeProvider,
  alpha,
  createTheme,
  useColorScheme,
  type PaletteOptions,
} from "@mui/material/styles";

declare module "@mui/material/styles" {
  interface CssThemeVariables {
    enabled: true;
  }
}

type ThemeMode = "light" | "dark";

type AppThemeContextValue = {
  mode: ThemeMode;
  toggleMode: () => void;
};

const AppThemeContext = createContext<AppThemeContextValue | null>(null);

const BRAND_PRIMARY = "#154e82";
const BRAND_PRIMARY_DARK = "#123f69";
const BRAND_PRIMARY_LIGHT = "#3576b0";

const lightPalette: PaletteOptions = {
  mode: "light",
  primary: {
    main: BRAND_PRIMARY,
    dark: BRAND_PRIMARY_DARK,
    light: BRAND_PRIMARY_LIGHT,
    contrastText: "#ffffff",
  },
  background: {
    default: "#f9fafb",
    paper: "#ffffff",
  },
  text: {
    primary: "#101828",
    secondary: "#6b7280",
    disabled: alpha("#101828", 0.38),
  },
  divider: "#e5e7eb",
  action: {
    hover: "#f9fafb",
    selected: "#eef4fb",
    disabledBackground: "#d5dbe3",
  },
};

const darkPalette: PaletteOptions = {
  mode: "dark",
  primary: {
    main: BRAND_PRIMARY_LIGHT,
    dark: BRAND_PRIMARY,
    light: "#6aa3d4",
    contrastText: "#ffffff",
  },
  background: {
    default: "#0f172a",
    paper: "#111827",
  },
  text: {
    primary: alpha("#ffffff", 0.92),
    secondary: alpha("#ffffff", 0.64),
    disabled: alpha("#ffffff", 0.38),
  },
  divider: alpha("#ffffff", 0.12),
  action: {
    hover: alpha("#ffffff", 0.06),
    selected: alpha("#ffffff", 0.1),
    disabledBackground: alpha("#ffffff", 0.12),
  },
};

// CSS variables let one theme object serve both modes. MUI swaps the active
// color scheme by flipping a `data-mui-color-scheme` attribute on <html>, so
// class hashes stay identical between server and client and hydration matches.
const theme = createTheme({
  cssVariables: {
    colorSchemeSelector: "data-mui-color-scheme",
  },
  colorSchemes: {
    light: { palette: lightPalette },
    dark: { palette: darkPalette },
  },
});

function AppThemeBridge({ children }: { children: ReactNode }) {
  const { mode, setMode } = useColorScheme();

  // useColorScheme returns mode=undefined on the server and on the first
  // client render before hydration finishes. Fall back to "light" so the
  // context shape stays { mode: "light" | "dark" } for consumers.
  const resolvedMode: ThemeMode = mode === "dark" ? "dark" : "light";

  const value = useMemo<AppThemeContextValue>(
    () => ({
      mode: resolvedMode,
      toggleMode: () => setMode(resolvedMode === "light" ? "dark" : "light"),
    }),
    [resolvedMode, setMode],
  );

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

export function AppThemeProvider({ children }: { children: ReactNode }) {
  return (
    <ThemeProvider
      theme={theme}
      defaultMode="light"
      modeStorageKey="theme-mode"
      forceThemeRerender
    >
      <CssBaseline />
      <AppThemeBridge>{children}</AppThemeBridge>
    </ThemeProvider>
  );
}

export function useAppTheme() {
  const context = use(AppThemeContext);

  if (!context) {
    throw new Error("useAppTheme must be used inside AppThemeProvider");
  }

  return context;
}
