import MenuList, {
  type MenuListProps,
} from '@material-hu/components/composed-components/MenuList';
import TableCell from '@material-hu/components/design-system/Table/components/TableCell';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { CertificateAction, CertificateStatus } from '../../../constants';
import { type LearningCertificateListItem } from '../../../types';
import { isLearningCertificateInUse } from '../../../utils';

import { type CertificateDialogActions } from './index';

type TableRowActionsProps = {
  certificate: LearningCertificateListItem;
  dialogActions: CertificateDialogActions;
};

export const TableRowActions = ({
  certificate,
  dialogActions,
}: TableRowActionsProps) => {
  const { t } = useLokaliseTranslation('learning');

  const { id: certificateId, name: certificateName, status } = certificate;
  const isActive = status === CertificateStatus.ACTIVE;
  const inUse = isLearningCertificateInUse(certificate);

  const { openStatusDialog, openDeleteDialog, openInUseDialog } = dialogActions;

  const handleToggleStatus = () => {
    if (!isActive) {
      openStatusDialog({
        certificateId,
        certificateName,
        action: CertificateAction.ACTIVATE,
      });
      return;
    }

    if (inUse) {
      openInUseDialog({
        certificateId,
        certificateName,
        action: CertificateAction.DEACTIVATE,
      });
      return;
    }

    openStatusDialog({
      certificateId,
      certificateName,
      action: CertificateAction.DEACTIVATE,
    });
  };

  const handleDelete = () => {
    if (inUse) {
      openInUseDialog({
        certificateId,
        certificateName,
        action: CertificateAction.DELETE,
      });
      return;
    }

    openDeleteDialog({ certificateId, certificateName });
  };

  const options: MenuListProps['options'] = [
    {
      title: t(isActive ? 'general:deactivate' : 'general:activate'),
      onClick: handleToggleStatus,
    },
    {
      title: t('general:delete'),
      onClick: handleDelete,
    },
  ];

  return (
    <TableCell
      sx={{ width: 60 }}
      align="right"
      onClick={e => e.stopPropagation()}
    >
      <MenuList
        options={options}
        position="right"
      />
    </TableCell>
  );
};
