import { createTheme, responsiveFontSizes, Shadows } from '@mui/material/styles';
import { LIGHT_PALETTE, DARK_PALETTE } from './colors';
import { TYPOGRAPHY_LTR, TYPOGRAPHY_RTL } from './typography';

/*
 * Teal-tinted elevation — replaces MUI's default grey shadow stack across
 * EVERY component that reads theme.shadows[n] (Paper, Card, Dialog, Menu,
 * Popover, AppBar elevation, Autocomplete…), not just the ones this file
 * overrides directly. Tiered onto the three --bal-shadow-* steps (tokens.css)
 * so low elevations (cards) stay subtle and high ones (dialogs, menus) read
 * clearly raised without ever going stock-MUI grey.
 */
const TEAL_SHADOWS = Array.from({ length: 25 }, (_, index) => {
  if (index === 0) return 'none';
  if (index <= 4) return 'var(--bal-shadow-1)';
  if (index <= 12) return 'var(--bal-shadow-2)';
  return 'var(--bal-shadow-3)';
}) as unknown as Shadows;

/*
 * Theme factory — called twice at module load (ltr + rtl) so components can
 * pick the right theme without re-creating it on every render.
 *
 * cssVariables.colorSchemeSelector: 'data-mui-color-scheme'
 *   → MUI v9 sets data-mui-color-scheme="dark"|"light" on <html>.
 *     (The shorthand 'data' produces boolean attrs data-dark/data-light which
 *      our CSS selectors never match — must use the explicit attribute name.)
 *
 * direction
 *   → MUI flips inline-start/end padding for components that care.
 *   → ThemeProvider pairs this with a direction-aware Emotion cache that
 *     runs stylis-plugin-rtl so all generated CSS is mirrored correctly.
 *
 * Every override below references `var(--bal-*)` tokens (tokens.css) — never
 * a raw hex — and only logical CSS properties, so the same override is
 * correct in both APP_THEME_LTR and APP_THEME_RTL.
 */
function createAppTheme(direction: 'ltr' | 'rtl') {
  const theme = createTheme({
    cssVariables: {
      // MUI v9: 'data' produces boolean attrs (data-dark / data-light) which our
      // CSS never matches. An explicit attribute name produces the keyed form:
      // data-mui-color-scheme="dark" — matching tokens.css selectors exactly.
      colorSchemeSelector: 'data-mui-color-scheme',
    },
    colorSchemes: {
      light: { palette: LIGHT_PALETTE },
      dark:  { palette: DARK_PALETTE  },
    },
    defaultColorScheme: 'light',
    typography: direction === 'rtl' ? TYPOGRAPHY_RTL : TYPOGRAPHY_LTR,
    shape: { borderRadius: 10 }, // house radius — mirrors --bal-radius-md
    direction,
    shadows: TEAL_SHADOWS,
    components: {
      MuiCssBaseline: {
        styleOverrides: {
          // Today exactly one hand-rolled :focus-visible rule exists in the app
          // (NurseResultCard). This makes keyboard focus uniform everywhere.
          '*:focus-visible': {
            outline: '2px solid var(--bal-focus-ring)',
            outlineOffset: '2px',
          },
        },
      },
      MuiButton: {
        defaultProps: { disableElevation: true },
        styleOverrides: {
          root: {
            borderRadius: 'var(--bal-radius-sm)',
            paddingInline: 20,
            paddingBlock: 9,
          },
        },
      },
      MuiPaper: {
        styleOverrides: {
          root: {
            backgroundImage: 'none',
            border: '1px solid var(--bal-divider)',
          },
        },
      },
      MuiDrawer: {
        styleOverrides: {
          paper: {
            backgroundColor: 'var(--bal-bg-default)',
            backgroundImage: 'none',
            borderInlineEnd: '1px solid var(--bal-divider)',
            borderInlineStart: '1px solid var(--bal-divider)',
          },
        },
      },
      MuiBottomNavigationAction: {
        styleOverrides: {
          root: {
            color: 'var(--bal-text-secondary)',
            '&.Mui-selected': { color: 'var(--bal-primary)' },
          },
          label: {
            '&.Mui-selected': { fontWeight: 700 },
          },
        },
      },
      MuiAppBar: {
        defaultProps: { color: 'transparent', elevation: 0 },
        styleOverrides: {
          root: {
            backgroundColor: 'var(--bal-bg-paper)',
            backgroundImage: 'none',
            color: 'var(--bal-text-primary)',
            borderBottom: '1px solid var(--bal-divider)',
          },
        },
      },
      MuiOutlinedInput: {
        styleOverrides: {
          root: {
            borderRadius: 'var(--bal-radius-sm)',
            '& .MuiOutlinedInput-notchedOutline': { borderColor: 'var(--bal-divider)' },
            '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: 'var(--bal-primary)' },
          },
        },
      },
      MuiChip: {
        styleOverrides: {
          root: { fontWeight: 500, borderRadius: 'var(--bal-radius-sm)' },
          outlined: { borderColor: 'var(--bal-divider)' },
          filled: ({ ownerState }: { ownerState: { color?: string } }) =>
            !ownerState.color || ownerState.color === 'default'
              ? { backgroundColor: 'var(--bal-primary-soft)', color: 'var(--bal-primary)' }
              : {},
        },
      },
      MuiToggleButton: {
        styleOverrides: {
          root: {
            border: '1px solid var(--bal-divider)',
            textTransform: 'none',
            '&.Mui-selected': {
              backgroundColor: 'var(--bal-primary-soft)',
              color: 'var(--bal-primary)',
            },
            '&.Mui-selected:hover': { backgroundColor: 'var(--bal-primary-soft)' },
          },
        },
      },
      MuiListItemButton: {
        styleOverrides: {
          root: {
            borderRadius: 'var(--bal-radius-sm)',
            '&.Mui-selected': {
              backgroundColor: 'var(--bal-primary-soft)',
              color: 'var(--bal-primary)',
            },
            '&.Mui-selected:hover': { backgroundColor: 'var(--bal-primary-soft)' },
          },
        },
      },
      MuiDialog: {
        styleOverrides: {
          paper: {
            borderRadius: 'var(--bal-radius-lg)',
            margin: 16,
            width: 'calc(100% - 32px)',
          },
        },
      },
      MuiTabs: {
        styleOverrides: {
          indicator: {
            height: 3,
            borderRadius: '3px 3px 0 0',
          },
        },
      },
      MuiTab: {
        styleOverrides: {
          root: { minHeight: 48, textTransform: 'none' },
        },
      },
      MuiAlert: {
        styleOverrides: {
          root: { borderRadius: 'var(--bal-radius-sm)' },
        },
      },
      MuiStepIcon: {
        styleOverrides: {
          root: {
            color: 'var(--bal-divider)',
            '&.Mui-active': { color: 'var(--bal-primary)' },
            '&.Mui-completed': { color: 'var(--bal-primary)' },
          },
        },
      },
      MuiSkeleton: {
        styleOverrides: {
          root: { backgroundColor: 'var(--bal-primary-soft)' },
        },
      },
      MuiTooltip: {
        styleOverrides: {
          tooltip: {
            backgroundColor: 'var(--bal-text-primary)',
            color: 'var(--bal-bg-paper)',
            borderRadius: 'var(--bal-radius-sm)',
            fontSize: '0.75rem',
          },
          arrow: { color: 'var(--bal-text-primary)' },
        },
      },
    },
  });

  return responsiveFontSizes(theme);
}

export const APP_THEME_LTR = createAppTheme('ltr');
export const APP_THEME_RTL = createAppTheme('rtl');

export default APP_THEME_LTR;
