import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { ConfirmDialog, api, formatError } from '@blocklet/payment-react';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import ClickBoundary from '../click-boundary';
import Actions from '../actions';
import TaxRateEdit from '../../pages/admin/tax/edit';

type TaxRate = {
  id: string;
  display_name: string;
  description?: string;
  country: string;
  state?: string;
  postal_code?: string;
  tax_code?: string;
  percentage: number;
  active: boolean;
  invoice_count?: number;
  metadata?: Record<string, any>;
  created_at?: string;
  updated_at?: string;
};

type Props = {
  data: TaxRate;
  onChange?: () => void;
};

export default function TaxRateActions({ data, onChange = () => {} }: Props) {
  const { t } = useLocaleContext();
  const navigate = useNavigate();
  const [state, setState] = useState<{ action: '' | 'toggle' | 'delete' | 'edit'; loading: boolean }>({
    action: '',
    loading: false,
  });

  const finish = () => {
    setState({ action: '', loading: false });
    onChange();
  };

  const handleToggle = async () => {
    try {
      setState({ action: 'toggle', loading: true });
      await api.put(`/api/tax-rates/${data.id}`, { active: !data.active });
      Toast.success(t('admin.taxRate.updated'));
      finish();
    } catch (error) {
      console.error(error);
      Toast.error(formatError(error));
      setState({ action: '', loading: false });
    }
  };

  const handleDelete = async () => {
    try {
      setState({ action: 'delete', loading: true });
      await api.delete(`/api/tax-rates/${data.id}`);
      Toast.success(t('admin.taxRate.deleted'));
      finish();
    } catch (error) {
      console.error(error);
      Toast.error(formatError(error));
      setState({ action: '', loading: false });
    }
  };

  const invoiceCount = Number(data.invoice_count) || 0;
  const canDelete = invoiceCount === 0;

  const actions = [
    {
      label: t('common.view'),
      color: 'primary',
      handler: () => navigate(`/admin/tax/${data.id}`),
    },
    {
      label: t('common.edit'),
      color: 'primary',
      handler: () => setState({ action: 'edit', loading: false }),
    },
    data.active
      ? {
          label: t('common.deactivate'),
          color: 'secondary',
          handler: () => setState({ action: 'toggle', loading: false }),
        }
      : {
          label: t('common.activate'),
          color: 'secondary',
          handler: () => setState({ action: 'toggle', loading: false }),
        },
    canDelete
      ? {
          label: t('common.delete'),
          color: 'error',
          handler: () => setState({ action: 'delete', loading: false }),
          divider: true,
        }
      : null,
  ].filter(Boolean) as any[];

  return (
    <ClickBoundary>
      <Actions actions={actions} variant="compact" />
      {state.action === 'edit' && (
        <TaxRateEdit
          id={data.id}
          initialData={data}
          onClose={() => setState({ action: '', loading: false })}
          onChange={onChange}
        />
      )}
      {state.action === 'toggle' && (
        <ConfirmDialog
          onConfirm={handleToggle}
          onCancel={() => setState({ action: '', loading: false })}
          loading={state.loading}
          title={data.active ? t('admin.taxRate.deactivateTitle') : t('admin.taxRate.activateTitle')}
          message={
            data.active
              ? t('admin.taxRate.deactivateMessage', { name: data.display_name })
              : t('admin.taxRate.activateMessage', { name: data.display_name })
          }
        />
      )}
      {state.action === 'delete' && (
        <ConfirmDialog
          onConfirm={handleDelete}
          onCancel={() => setState({ action: '', loading: false })}
          loading={state.loading}
          title={t('admin.taxRate.deleteTitle')}
          message={t('admin.taxRate.deleteMessage', { name: data.display_name })}
        />
      )}
    </ClickBoundary>
  );
}
