import { Menu, styled, Typography } from '@mui/material';
import { useState } from 'react';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { useMemoizedFn } from 'ahooks';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { translations } from '../../libs/locales';
import { DurationEnum } from '../../../@types';
import StatusMenuItem, { BaseStatusProps, StatusItem, StyledMenu } from './menu-item';

interface StatusDurationMenuProps extends BaseStatusProps {
  data: StatusItem;
}
function DurationMenu({ data, selected, onSelect }: StatusDurationMenuProps) {
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, _data = {}) => {
    return translate(translations, key, locale, 'en', _data);
  });
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const open = Boolean(anchorEl);

  const openSubMenu = (e: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(e.currentTarget);
  };

  const closeSubMenu = () => {
    setAnchorEl(null);
  };

  const onSelectStatus = (e: React.MouseEvent<HTMLElement>) => {
    openSubMenu(e);
  };

  const onSelectDuration = (e: React.MouseEvent<HTMLElement>, item: StatusItem) => {
    onSelect({
      ...(selected ?? {}),
      value: data.id,
      duration: item.id as DurationEnum,
    });
    closeSubMenu();
  };
  return (
    <>
      <StatusMenuItem icon={data.icon} selected={selected?.value === data.id} onClick={onSelectStatus}>
        {data.name}
      </StatusMenuItem>
      <StyledMenu
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        open={open}
        onClose={closeSubMenu}
        anchorEl={anchorEl}>
        <Typography
          component="span"
          sx={{
            color: 'text.secondary',
            pl: 2,
            fontSize: '14px',
          }}>
          {t('profile.removeStatusAfter')}
        </Typography>
        {data.children?.map((item) => (
          <StatusMenuItem
            key={item.id}
            selected={selected?.duration === item.id}
            onClick={(e) => onSelectDuration(e, item)}>
            {item.name}
          </StatusMenuItem>
        ))}
      </StyledMenu>
    </>
  );
}

export default DurationMenu;

export const MenuDiv = styled(Menu)`
  .MuiList-root {
    min-width: 160px;
  }
  .selected {
    background-color: ${({ theme }) => theme.palette.grey[50]};
  }
`;
