import { PopoverProps, Typography } from '@mui/material';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useMemoizedFn } from 'ahooks';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { UserMetadata } from '../../../@types';
import StatusDurationMenu from './duration-menu';
import StatusMenuItem, { BaseStatusProps, StatusItem, StyledMenu } from './menu-item';
import { translations } from '../../libs/locales';

interface StatusSelectorProps extends BaseStatusProps {
  data: Array<StatusItem>;
  open: boolean;
  anchorEl?: PopoverProps['anchorEl'];
}

function StatusSelector({ data, open, onSelect, anchorEl = undefined, selected }: StatusSelectorProps) {
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, _data = {}) => {
    return translate(translations, key, locale, 'en', _data);
  });
  const onSelectStatus = (v?: UserMetadata['status']) => {
    onSelect(v);
  };

  const renderMenuItems = () => {
    return data.map((item) => {
      if (item.children) {
        return <StatusDurationMenu key={item.id} data={item} selected={selected} onSelect={onSelectStatus} />;
      }
      return (
        <StatusMenuItem
          key={item.id}
          icon={item.icon}
          selected={selected?.value === item.id}
          onClick={() => onSelectStatus({ value: item.id })}>
          {item.name}
        </StatusMenuItem>
      );
    });
  };

  return (
    <StyledMenu open={open} onClose={() => onSelectStatus()} anchorEl={anchorEl}>
      <Typography
        component="span"
        sx={{
          color: 'text.secondary',
          pl: 2,
          fontSize: '14px',
        }}>
        {t('profile.setStatus')}
      </Typography>
      {renderMenuItems()}
    </StyledMenu>
  );
}

export default StatusSelector;
