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 type { LiteralUnion } from 'type-fest';

import { useEffect, useRef } from 'react';
import Actions from '../actions';
import ClickBoundary from '../click-boundary';

interface Vendor {
  id: string;
  vendor_key: string;
  vendor_type: string;
  name: string;
  description: string;
  app_url: string;
  status: 'active' | 'inactive';
  metadata: Record<string, any>;
  created_at: string;
  updated_at: string;
}

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

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

  const onToggleStatus = async () => {
    try {
      setState({ loading: true });
      const newStatus = data.status === 'active' ? 'inactive' : 'active';
      await api.put(`/api/vendors/${data.id}`, { ...data, status: newStatus }).then((res: any) => res.data);
      Toast.success(t('common.saved'));
      onChange(state.action);
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false, action: '' });
    }
  };

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

  const onTestConnectionRef = useRef(async () => {
    try {
      setState({ loading: true });
      const result = await api.post(`/api/vendors/${data.id}/test-connection`).then((res: any) => res.data);
      if (result.error) {
        Toast.error(result.error);
      } else {
        Toast.success(t('admin.vendor.testConnectionSuccess'));
      }
    } catch (err) {
      console.error(err);
      if (err.response?.data?.code === 'VENDOR_CONNECT_TEST_FAILED') {
        Toast.error(err.response?.data?.error);
      } else {
        Toast.error(formatError(err));
      }
    } finally {
      setState({ loading: false, action: '' });
    }
  });

  useEffect(() => {
    if (state.action === 'testConnection') {
      onTestConnectionRef.current();
    }
  }, [state.action]);

  return (
    <ClickBoundary>
      <Actions
        variant={variant}
        actions={[
          data.status === 'active'
            ? {
                label: t('admin.vendor.deactivate'),
                handler: () => setState({ action: 'toggle_status' }),
                color: 'primary',
              }
            : {
                label: t('admin.vendor.activate'),
                handler: () => setState({ action: 'toggle_status' }),
                color: 'primary',
              },
          {
            label: t('admin.vendor.delete'),
            handler: () => setState({ action: 'remove' }),
            color: 'error',
            divider: true,
          },
          {
            label: t('admin.vendor.testConnection'),
            handler: () => setState({ action: 'testConnection' }),
            color: 'primary',
          },
        ].filter(Boolean)}
      />
      {state.action === 'toggle_status' && (
        <ConfirmDialog
          onConfirm={onToggleStatus}
          onCancel={() => setState({ action: '' })}
          title={data.status === 'active' ? t('admin.vendor.deactivate') : t('admin.vendor.activate')}
          message={
            data.status === 'active'
              ? t('admin.vendor.deactivateTip', { name: data.name })
              : t('admin.vendor.activateTip', { name: data.name })
          }
          loading={state.loading}
        />
      )}
      {state.action === 'remove' && (
        <ConfirmDialog
          onConfirm={onRemove}
          onCancel={() => setState({ action: '' })}
          title={t('admin.vendor.delete')}
          message={t('admin.vendor.deleteTip', { name: data.name })}
          loading={state.loading}
        />
      )}
    </ClickBoundary>
  );
}
