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 { useNavigate } from 'react-router-dom';
import type { LiteralUnion } from 'type-fest';
import type { TMeter } from '@blocklet/payment-types';
import Actions from '../actions';
import ClickBoundary from '../click-boundary';

interface MeterActionsProps {
  data: TMeter;
  variant?: LiteralUnion<'compact' | 'normal', string>;
  onChange: (action?: string) => void;
}

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

  const createHandler = (action: string) => {
    return async () => {
      try {
        setState({ loading: true });

        if (action === 'delete') {
          await api.delete(`/api/meters/${data.id}`);
        } else {
          await api.put(`/api/meters/${data.id}/${action}`);
        }

        if (action === 'activate') {
          Toast.success(t('admin.meter.activated'));
        } else if (action === 'deactivate') {
          Toast.success(t('admin.meter.deactivated'));
        } else if (action === 'delete') {
          Toast.success(t('admin.meter.deleted'));
        }

        onChange(action);
      } catch (err) {
        console.error(err);
        Toast.error(formatError(err));
      } finally {
        setState({ loading: false, action: '' });
      }
    };
  };

  const handleCancel = () => {
    setState({ action: '' });
  };

  const actions = [
    {
      label: data.status === 'inactive' ? t('admin.meter.activate') : t('admin.meter.deactivate'),
      handler: () => setState({ action: data.status === 'inactive' ? 'activate' : 'deactivate' }),
      color: data.status === 'inactive' ? 'primary' : 'error',
    },
  ];

  if (variant === 'compact') {
    actions.push({
      label: t('admin.meter.view'),
      handler: () => navigate(`/admin/billing/${data.id}`),
      color: 'primary',
    });
  }

  return (
    <ClickBoundary>
      <Actions variant={variant} actions={actions} />

      {state.action === 'activate' && (
        <ConfirmDialog
          onConfirm={createHandler('activate')}
          onCancel={handleCancel}
          title={t('admin.meter.activate')}
          message={t('admin.meter.activateConfirm')}
          loading={state.loading}
          color="primary"
        />
      )}

      {state.action === 'deactivate' && (
        <ConfirmDialog
          onConfirm={createHandler('deactivate')}
          onCancel={handleCancel}
          title={t('admin.meter.deactivate')}
          message={t('admin.meter.deactivateConfirm')}
          loading={state.loading}
          color="warning"
        />
      )}
    </ClickBoundary>
  );
}
