import { type ReactNode, useMemo } from 'react';

import { createTheme as createMuiTheme } from '@material-hu/mui';
import { ThemeProvider, useTheme } from '@material-hu/mui/styles';
import { buildNewPalette } from '@material-hu/theme/hugo/newTokens';
import { createNewTheme } from '@material-hu/theme/material-hu';

const useNewTheme = () => {
  const theme = useTheme();

  // useMemo is needed to stop the theme from being recreated on every render
  // Use the same logic as createThemeConfig in theme/index.ts to ensure consistency
  return useMemo(() => {
    // Create the base new theme
    const baseTheme = createNewTheme({
      colorPreset: theme.palette.primary.main,
    });

    // Determine mode based on theme (same logic as createThemeConfig)
    // Get theme from the parent theme if available, default to light
    const mode = theme.palette.mode === 'dark' ? 'dark' : 'light';

    // Build new palette with the new tokens (same as createThemeConfig)
    // Pass primary color to ensure brand colors match the main theme
    const newPalette = buildNewPalette(mode, theme.palette.primary.main);

    // Extend the theme to include the new palette and propagate the parent
    // palette mode so MUI components (background, text, dividers) render with
    // the correct dark/light tokens. Without this, downstream components keep
    // the default light palette even when the parent theme is dark.
    const newTheme = createMuiTheme(baseTheme, {
      palette: {
        ...baseTheme.palette,
        mode,
        new: newPalette,
      },
    });

    const newThemeComponent = ({ children }: { children: ReactNode }) => (
      <ThemeProvider theme={newTheme}>{children}</ThemeProvider>
    );

    return newThemeComponent;
  }, [theme.palette.primary.main, theme.palette.mode]); // Include dependencies to update when theme changes
};

export default useNewTheme;
