import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { TRefundExpanded } from '@blocklet/payment-types';
import { useNavigate } from 'react-router-dom';
import type { LiteralUnion } from 'type-fest';

import { api, ConfirmDialog, formatError } from '@blocklet/payment-react';
import { useSetState } from 'ahooks';
import Toast from '@arcblock/ux/lib/Toast';
import Actions from '../actions';
import ClickBoundary from '../click-boundary';

type Props = {
  data: TRefundExpanded;
  onChange?: (action: string) => void;
  variant?: LiteralUnion<'compact' | 'normal', string>;
};

export default function RefundActions({ data, variant = 'compact', onChange = () => {} }: Props) {
  const { t } = useLocaleContext();
  const navigate = useNavigate();
  const [state, setState] = useSetState({
    action: '',
    loading: false,
  });

  const actions = [
    {
      label: t('admin.customer.view'),
      handler: () => navigate(`/admin/customers/${data.customer_id}`),
      color: 'primary',
      disabled: false,
    },
  ];
  if (variant === 'compact') {
    actions.push({
      label: t('admin.refund.view'),
      handler: () => navigate(`/admin/payments/${data.id}`),
      color: 'primary',
      disabled: false,
    });
  }
  if (!['succeeded', 'canceled'].includes(data.status)) {
    actions.push({
      label: t('admin.paymentIntent.cancelRefund'),
      handler: () => setState({ action: 'cancel' }),
      color: 'error',
      disabled: false,
    });
  }

  const onCancel = async () => {
    try {
      setState({ loading: true });
      await api.post(`/api/refunds/${data?.id}/cancel`);
      Toast.success(t('admin.paymentIntent.refundCanceled'));
      // @ts-ignore
      onChange(state.action);
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false, action: '' });
    }
  };

  return (
    <ClickBoundary>
      <Actions variant={variant} actions={actions} />
      {state.action === 'cancel' && (
        <ConfirmDialog
          onConfirm={onCancel}
          onCancel={() => setState({ action: '' })}
          title={t('admin.paymentIntent.cancelRefund')}
          message={t('admin.paymentIntent.refundCanceledTip')}
          loading={state.loading}
        />
      )}
    </ClickBoundary>
  );
}
