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 Actions from '../actions';
import ClickBoundary from '../click-boundary';

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

export default function PassportActions(rawProps: Props) {
  const props = Object.assign(
    {
      variant: 'compact',
    },
    rawProps
  );

  const { t } = useLocaleContext();

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

  const onUnassign = async () => {
    try {
      setState({ loading: true });
      // eslint-disable-next-line react/prop-types
      await api.delete(`/api/passports/assign/${props.data.name}`).then((res: any) => res.data);
      Toast.success(t('common.saved'));
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false, action: '' });
    }
  };

  const actions = [
    {
      label: t('admin.passport.unassign'),
      handler: () => setState({ action: 'unassign' }),
      color: 'error',
    },
  ];

  return (
    <ClickBoundary>
      {/* eslint-disable-next-line react/prop-types */}
      <Actions variant={props.variant} actions={actions} />
      {state.action === 'unassign' && (
        <ConfirmDialog
          onConfirm={onUnassign}
          onCancel={() => setState({ action: '' })}
          title={t('admin.passport.unassign')}
          message={t('admin.passport.unassignTip')}
        />
      )}
    </ClickBoundary>
  );
}
