import { polyfillCountryFlagEmojis } from 'country-flag-emoji-polyfill';
import { merge } from 'lodash-es';
import {
  createTheme as createMuiTheme,
  responsiveFontSizes,
  type Theme,
  type ThemeOptions,
} from '@material-hu/mui';
import grey from '@material-hu/mui/colors/grey';
import orange from '@material-hu/mui/colors/orange';
import { colorPalette } from '@material-hu/theme/hugo/colors';
import { buildNewPalette } from '@material-hu/theme/hugo/newTokens';
// Import theme augmentation to ensure types are available
import '@material-hu/theme/hugo/theme-augmentation';

import { type Direction } from '@material-hu/mui/styles';

import { THEMES } from 'src/constants/env';

import { darkShadows, lightShadows } from './shadows';

type ThemeConfig = {
  direction?: Direction;
  responsiveFontSizes?: boolean;
  roundedCorners?: boolean;
  theme?: string;
  primary?: string;
};

const baseOptions: ThemeOptions = {
  direction: 'ltr',
  components: {
    MuiAvatar: {
      styleOverrides: {
        fallback: {
          height: '75%',
          width: '75%',
        },
      },
    },
    MuiButton: {
      styleOverrides: {
        root: {
          textTransform: 'none',
        },
      },
    },
    MuiCardHeader: {
      defaultProps: {
        titleTypographyProps: {
          variant: 'h6',
        },
      },
    },
    MuiLinearProgress: {
      styleOverrides: {
        root: {
          borderRadius: 3,
          overflow: 'hidden',
        },
      },
    },
    MuiListItemIcon: {
      styleOverrides: {
        root: {
          minWidth: 'auto',
          marginRight: '16px',
        },
      },
    },
    /*     MuiTableRow: {
          styleOverrides: {
            root: {
              height: '100%',
            },
            head: {
              height: '100%',
            },
          },
        }, */
  },
  typography: {
    button: {
      fontWeight: 600,
    },
    fontFamily:
      '"Twemoji Country Flags", -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"',
    h1: {
      fontWeight: 600,
      fontSize: '3.5rem',
    },
    h2: {
      fontWeight: 600,
      fontSize: '3rem',
    },
    h3: {
      fontWeight: 600,
      fontSize: '2.25rem',
    },
    h4: {
      fontWeight: 600,
      fontSize: '2rem',
    },
    h5: {
      fontWeight: 600,
      fontSize: '1.5rem',
    },
    h6: {
      fontWeight: 600,
      fontSize: '1.125rem',
    },
    overline: {
      fontWeight: 600,
    },
  },
};

const themesOptions: Record<string, ThemeOptions> = {
  [THEMES.LIGHT]: {
    components: {
      MuiInputBase: {
        styleOverrides: {
          input: {
            '&::placeholder': {
              opacity: 0.86,
              color: '#42526e',
            },
          },
        },
      },
    },
    palette: {
      action: {
        active: '#6b778c',
        selected: grey[200],
      },
      background: {
        default: '#f4f5f7',
        paper: '#ffffff',
      },
      mode: 'light',
      primary: {
        contrastText: '#ffffff',
        main: '#5664d2',
      },
      secondary: {
        main: grey[600],
      },
      warning: {
        main: orange[500],
      },
      error: {
        contrastText: '#ffffff',
        main: '#f44336',
      },
      success: {
        contrastText: '#ffffff',
        main: '#4caf50',
      },
      info: {
        main: '#29b6f6',
        dark: '#01579b',
      },
      text: {
        primary: '#172b4d',
        secondary: '#6b778c',
      },
    },
    shadows: lightShadows,
  },
  [THEMES.DARK]: {
    components: {
      MuiTableCell: {
        styleOverrides: {
          root: {
            borderBottom: '1px solid rgba(145, 158, 171, 0.24)',
          },
        },
      },
    },
    palette: {
      background: {
        default: '#171c24',
        paper: '#222b36',
      },
      divider: 'rgba(145, 158, 171, 0.24)',
      error: {
        contrastText: '#ffffff',
        main: '#f44336',
      },
      mode: 'dark',
      primary: {
        contrastText: '#ffffff',
        main: '#688eff',
        light: '#DFEDFF',
      },
      success: {
        contrastText: '#ffffff',
        main: '#4caf50',
      },
      text: {
        primary: '#ffffff',
        secondary: '#919eab',
      },
      warning: {
        contrastText: '#ffffff',
        main: '#ff9800',
      },
    },
    shadows: darkShadows,
  },
  [THEMES.NATURE]: {
    components: {
      MuiTableCell: {
        styleOverrides: {
          root: {
            borderBottom: '1px solid rgba(145, 158, 171, 0.24)',
          },
        },
      },
    },
    palette: {
      background: {
        default: '#1c2531',
        paper: '#293142',
      },
      divider: 'rgba(145, 158, 171, 0.24)',
      error: {
        contrastText: '#ffffff',
        main: '#f44336',
      },
      mode: 'dark',
      primary: {
        contrastText: '#ffffff',
        main: '#01ab56',
        light: '#DFEDFF',
      },
      success: {
        contrastText: '#ffffff',
        main: '#4caf50',
      },
      text: {
        primary: '#ffffff',
        secondary: '#919eab',
      },
      warning: {
        contrastText: '#ffffff',
        main: '#ff9800',
      },
    },
    shadows: darkShadows,
  },
};

export const createThemeConfig = (config: ThemeConfig = {}): Theme => {
  let themeOptions = themesOptions[config.theme || THEMES.LIGHT];

  polyfillCountryFlagEmojis();

  if (!themeOptions) {
    console.error(new Error(`The theme ${config.theme} is not valid`));
    themeOptions = themesOptions[THEMES.LIGHT];
  }

  // Determine mode based on theme
  const mode = config.theme === THEMES.LIGHT ? 'light' : 'dark';

  // Build new palette with the new tokens
  const newPalette = buildNewPalette(mode, config.primary);

  if (config.primary && themeOptions.palette) {
    themeOptions.palette.primary = {
      ...themeOptions.palette.primary,
      main: config.primary,
    };
  }

  // Merge theme options first
  const mergedOptions = merge({}, baseOptions, themeOptions, {
    ...(config.roundedCorners && {
      shape: {
        borderRadius: 16,
      },
    }),
    direction: config.direction,
  });

  // Create theme following the same pattern as createHuGoTheme in material-hu
  // This ensures the new palette is included from the start and preserved by MUI
  const theme = createMuiTheme({
    ...mergedOptions,
    palette: {
      ...colorPalette, // Preserve old theme properties (hugoBackground, textColors, border, etc.)
      ...(mergedOptions.palette || {}), // Include any palette options from mergedOptions
      mode, // Set the mode
      new: newPalette, // Add new tokens - this must be included in the initial createMuiTheme call
    },
  });

  // Apply responsive font sizes if needed
  if (config.responsiveFontSizes) {
    return responsiveFontSizes(theme);
  }

  return theme;
};
