import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { ConfirmDialog, api, formatError } from '@blocklet/payment-react';
import { useSetState } from 'ahooks';
import { dispatch } from 'use-bus';
import Actions from '../../../../components/actions';

type Props = {
  data: any;
  onChange: Function;
  variant?: string;
};

export default function PromotionCodeActions({ data, onChange, variant = 'compact' }: Props) {
  const { t } = useLocaleContext();

  const canEdit = !data.locked && data.active;
  const canDelete = !data.locked;
  const canArchive = data.active;

  const [state, setState] = useSetState({
    action: '',
    loading: false,
  });

  const onArchivePromotionCode = async () => {
    try {
      setState({ loading: true });
      await api.put(`/api/promotion-codes/${data.id}/archive`).then((res: any) => res.data);
      Toast.success(t('common.saved'));
      dispatch('promotion-code.updated');
      onChange(state.action);
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false, action: '' });
    }
  };

  const onDeletePromotionCode = async () => {
    try {
      setState({ loading: true });
      await api.delete(`/api/promotion-codes/${data.id}`).then((res: any) => res.data);
      Toast.success(t('common.removed'));
      dispatch('promotion-code.deleted');
      onChange(state.action);
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false, action: '' });
    }
  };

  const onEditPromotionCode = () => {
    setState({ action: 'edit' });
    onChange('edit', data);
  };

  const actions = [
    {
      label: t('admin.promotionCode.edit'),
      handler: onEditPromotionCode,
      color: canEdit ? 'text.primary' : 'text.disabled',
      disabled: !canEdit,
    },
    {
      label: t('admin.promotionCode.archive'),
      handler: () => setState({ action: 'archive' }),
      color: canArchive ? 'text.primary' : 'text.disabled',
      disabled: !canArchive,
    },
    {
      label: t('admin.promotionCode.delete'),
      handler: () => setState({ action: 'delete' }),
      color: canDelete ? 'error.main' : 'text.disabled',
      disabled: !canDelete,
    },
  ];

  return (
    <>
      <Actions variant={variant} actions={actions} />
      {state.action === 'archive' && (
        <ConfirmDialog
          onConfirm={onArchivePromotionCode}
          onCancel={() => setState({ action: '' })}
          title={t('admin.promotionCode.archive')}
          message={t('admin.promotionCode.archiveTip')}
        />
      )}
      {state.action === 'delete' && (
        <ConfirmDialog
          onConfirm={onDeletePromotionCode}
          onCancel={() => setState({ action: '' })}
          title={t('admin.promotionCode.delete')}
          message={t('admin.promotionCode.deleteTip')}
        />
      )}
    </>
  );
}
