import React, { useEffect } from 'react';
import {
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  IconButton,
} from '@chakra-ui/react';
import { EditIcon } from '@chakra-ui/icons';
import { useTranslation } from 'react-i18next';

import { useDeleteMasterMutation } from '../../__data__/service/api';
import useShowToast from '../../hooks/useShowToast';

interface MasterActionsMenu {
  id: string;
}

const MasterActionsMenu = ({ id }: MasterActionsMenu) => {
  const { t } = useTranslation('~', {
    keyPrefix: 'dry-wash.arm.master.table.actionsMenu',
  });

  const [deleteMaster, { isSuccess, isError, error, isLoading }] =
    useDeleteMasterMutation();

  const showToast = useShowToast();

  const handleClickDelete = async () => {
    await deleteMaster({ id });
  };

  useEffect(() => {
    if (isSuccess) {
      showToast(t('toast.success'), 'success');
    }
  }, [isSuccess]);

  useEffect(() => {
    if (isError) {
      showToast(t('toast.error.title'), 'error', t('toast.error.description'));
      console.error(error);
    }
  }, [isError]);

  return (
    <Menu>
      <MenuButton icon={<EditIcon />} as={IconButton} variant='outline' />
      <MenuList>
        <MenuItem onClick={handleClickDelete} isDisabled={isLoading}>
          {t('delete')}
        </MenuItem>
      </MenuList>
    </Menu>
  );
};

export default MasterActionsMenu;
