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 { TPricingTableExpanded } from '@blocklet/payment-types';
import { useSetState } from 'ahooks';
import Copy from 'copy-to-clipboard';
import type { LiteralUnion } from 'type-fest';
import { joinURL } from 'ufo';

import Actions from '../actions';
import ClickBoundary from '../click-boundary';
import AssignPassportDialog from '../passport/assign';
import RenamePricingTable from './rename';

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

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

  const onUpdate = async (updates: TPricingTableExpanded) => {
    try {
      setState({ loading: true });
      await api.put(`/api/pricing-tables/${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/pricing-tables/${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/pricing-tables/${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 onCopyLink = () => {
    Copy(joinURL(window.blocklet.appUrl, window.blocklet.prefix, `/checkout/pricing-table/${data.id}`));
    Toast.success(t('common.copied'));
  };

  const onOpenLink = () => {
    window.open(
      joinURL(window.blocklet.appUrl, window.blocklet.prefix, `/checkout/pricing-table/${data.id}`),
      '_blank'
    );
  };
  return (
    <ClickBoundary>
      <Actions
        variant={variant}
        actions={[
          {
            label: t('admin.pricingTable.openLink'),
            handler: onOpenLink,
            color: 'primary',
          },
          // {
          //   label: t('admin.pricingTable.edit'),
          //   handler: () => setState({ action: 'edit' }),
          //   color: 'primary',
          //   disabled: true,
          // },
          {
            label: t('admin.pricingTable.copyLink'),
            handler: onCopyLink,
            color: 'primary',
          },
          { label: t('admin.pricingTable.rename'), handler: () => setState({ action: 'rename' }), color: 'primary' },
          { label: t('admin.pricingTable.archive'), handler: () => setState({ action: 'archive' }), color: 'primary' },
          {
            label: t('admin.pricingTable.remove'),
            handler: () => setState({ action: 'remove' }),
            color: 'error',
            divider: true,
          },
          {
            label: t('admin.passport.assign'),
            handler: () => setState({ action: 'assign' }),
            color: 'primary',
            disabled: !data.active,
          },
        ]}
      />
      {state.action === 'rename' && (
        <RenamePricingTable
          data={data}
          loading={state.loading}
          onSave={onUpdate}
          onCancel={() => setState({ action: '' })}
        />
      )}
      {state.action === 'assign' && <AssignPassportDialog id={data.id} onCancel={() => setState({ action: '' })} />}
      {state.action === 'archive' && (
        <ConfirmDialog
          onConfirm={onArchive}
          onCancel={() => setState({ action: '' })}
          title={t('admin.pricingTable.archive')}
          message={t('admin.pricingTable.archiveTip')}
          loading={state.loading}
        />
      )}
      {state.action === 'remove' && (
        <ConfirmDialog
          onConfirm={onRemove}
          onCancel={() => setState({ action: '' })}
          title={t('admin.pricingTable.remove')}
          message={t('admin.pricingTable.removeTip')}
          loading={state.loading}
        />
      )}
    </ClickBoundary>
  );
}
