import { HeaderButton } from './HeaderButton';
import { usePopoverState } from '@/hooks';
import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';
import { Menu, MenuItem, Stack, Typography } from '@mui/material';
import { useLocaleState, useLocales } from 'ra-core';
import { Fragment } from 'react/jsx-runtime';

type LocaleButtonProps = {
  onClick?: (locale: string, handleClose: () => void) => void;
};

function LocaleButton({ onClick = undefined }: LocaleButtonProps): JSX.Element | null {
  const { open, anchorEl, handleClose, handleToggle } = usePopoverState();
  const [locale, setLocale] = useLocaleState();
  const locales = useLocales();
  if (locales.length === 0) {
    return null;
  }
  function handleChooseLocale(locale: string) {
    if (onClick) {
      onClick(locale, handleClose);
      return;
    }

    setLocale(locale);
    handleClose();
  }
  return (
    <Fragment>
      <HeaderButton value="locale" onClick={handleToggle} sx={{ minWidth: 'auto' }}>
        <Stack direction="row" spacing={0.5}>
          <Typography variant="body1">{locale.toUpperCase()}</Typography>
          {open ? <CaretUpOutlined /> : <CaretDownOutlined />}
        </Stack>
      </HeaderButton>
      <Menu id="menu-appbar" anchorEl={anchorEl} keepMounted open={open} onClose={handleClose}>
        {locales.map((locale, index) => (
          <MenuItem key={index} onClick={() => handleChooseLocale(locale.locale)}>
            {locale.name}
          </MenuItem>
        ))}
      </Menu>
    </Fragment>
  );
}

export { LocaleButton };
