import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { ConfirmDialog, api, formatError } from '@blocklet/payment-react';
import type { TProduct, TProductExpanded } from '@blocklet/payment-types';
import { useSetState } from 'ahooks';
import type { LiteralUnion } from 'type-fest';
import { isEmpty } from 'lodash';

import Actions from '../actions';
import ClickBoundary from '../click-boundary';
import AssignPassportDialog from '../passport/assign';
import EditProduct from './edit';

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

export default function ProductActions({ data, variant = 'compact', onChange }: ProductActionProps) {
  const isLocked = data.locked || (!isEmpty(data.prices) && data.prices.some((x) => x.locked));
  const { t } = useLocaleContext();
  const [state, setState] = useSetState({
    action: '',
    loading: false,
  });

  const onUpdate = async (updates: TProduct) => {
    try {
      setState({ loading: true });
      await api.put(`/api/products/${data.id}`, updates).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 onArchive = async () => {
    try {
      setState({ loading: true });
      await api.put(`/api/products/${data.id}/archive`).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/products/${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: '' });
    }
  };

  return (
    <ClickBoundary>
      <Actions
        variant={variant}
        actions={[
          {
            label: t('admin.product.edit'),
            handler: () => setState({ action: 'edit' }),
            color: 'primary',
            disabled: !data.active,
            divider: true,
          },
          data.active
            ? { label: t('admin.product.archive'), handler: () => setState({ action: 'archive' }), color: 'primary' }
            : { label: t('admin.product.unarchive'), handler: () => setState({ action: 'unarchive' }), color: 'primary' }, // prettier-ignore
          {
            label: t('admin.product.remove'),
            handler: () => setState({ action: 'remove' }),
            disabled: isLocked,
            color: isLocked ? 'text.disabled' : 'error',
            divider: true,
          },
          {
            label: t('admin.passport.assign'),
            handler: () => setState({ action: 'assign' }),
            color: 'primary',
            disabled: !data.active,
          },
        ].filter(Boolean)}
      />
      {state.action === 'edit' && (
        <EditProduct
          product={data}
          loading={state.loading}
          onSave={onUpdate}
          onCancel={() => setState({ action: '' })}
        />
      )}
      {state.action === 'archive' && (
        <ConfirmDialog
          onConfirm={onArchive}
          onCancel={() => setState({ action: '' })}
          title={t('admin.product.archive')}
          message={t('admin.product.archiveTip')}
          loading={state.loading}
        />
      )}
      {state.action === 'unarchive' && (
        <ConfirmDialog
          onConfirm={onArchive}
          onCancel={() => setState({ action: '' })}
          title={t('admin.product.unarchive')}
          message={t('admin.product.unarchiveTip')}
          loading={state.loading}
        />
      )}
      {state.action === 'remove' && (
        <ConfirmDialog
          onConfirm={onRemove}
          onCancel={() => setState({ action: '' })}
          title={t('admin.product.remove')}
          message={t('admin.product.removeTip')}
          loading={state.loading}
        />
      )}
      {state.action === 'assign' && <AssignPassportDialog id={data.id} onCancel={() => setState({ action: '' })} />}
    </ClickBoundary>
  );
}
