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 { TPaymentLinkExpanded } 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 RenamePaymentLink from './rename';

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

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

  const onUpdate = async (updates: TPaymentLinkExpanded) => {
    try {
      setState({ loading: true });
      await api.put(`/api/payment-links/${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/payment-links/${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/payment-links/${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 onTogglePromotionCodes = async () => {
    try {
      setState({ loading: true });
      await api
        .put(`/api/payment-links/${data.id}`, {
          allow_promotion_codes: !data.allow_promotion_codes,
        })
        .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 onToggleSkipPaymentMethod = async () => {
    const currentMetadata = (data.metadata || {}) as Record<string, any>;
    const isEnabled = currentMetadata.allow_skip_payment_method === 'true';
    try {
      setState({ loading: true });
      await api
        .put(`/api/payment-links/${data.id}`, {
          metadata: { ...currentMetadata, allow_skip_payment_method: isEnabled ? 'false' : 'true' },
        })
        .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 onCopyLink = () => {
    Copy(joinURL(window.blocklet.appUrl, window.blocklet.prefix, `/checkout/pay/${data.id}`));
    Toast.success(t('common.copied'));
  };

  const onOpenLink = () => {
    window.open(joinURL(window.blocklet.appUrl, window.blocklet.prefix, `/checkout/pay/${data.id}`));
  };

  return (
    <ClickBoundary>
      <Actions
        variant={variant}
        actions={[
          {
            label: t('admin.paymentLink.openLink'),
            handler: onOpenLink,
            color: 'primary',
          },
          // {
          //   label: t('admin.paymentLink.edit'),
          //   handler: () => setState({ action: 'edit' }),
          //   color: 'primary',
          //   disabled: true,
          // },
          {
            label: t('admin.paymentLink.copyLink'),
            handler: onCopyLink,
            color: 'primary',
          },
          { label: t('admin.paymentLink.rename'), handler: () => setState({ action: 'rename' }), color: 'primary' },
          { label: t('admin.paymentLink.archive'), handler: () => setState({ action: 'archive' }), color: 'primary' },
          {
            label: t('admin.paymentLink.remove'),
            handler: () => setState({ action: 'remove' }),
            color: 'error',
            divider: true,
          },
          {
            label: data.allow_promotion_codes
              ? t('admin.paymentLink.disablePromotionCodes')
              : t('admin.paymentLink.enablePromotionCodes'),
            handler: () => setState({ action: 'togglePromotionCodes' }),
            color: 'primary',
          },
          {
            label:
              (data.metadata as Record<string, any>)?.allow_skip_payment_method === 'true'
                ? t('admin.paymentLink.disableSkipPaymentMethod')
                : t('admin.paymentLink.enableSkipPaymentMethod'),
            handler: () => setState({ action: 'toggleSkipPaymentMethod' }),
            color: 'primary',
          },
          {
            label: t('admin.passport.assign'),
            handler: () => setState({ action: 'assign' }),
            color: 'primary',
            disabled: !data.active,
          },
        ]}
      />
      {state.action === 'rename' && (
        <RenamePaymentLink
          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.paymentLink.archive')}
          message={t('admin.paymentLink.archiveTip')}
          loading={state.loading}
        />
      )}
      {state.action === 'remove' && (
        <ConfirmDialog
          onConfirm={onRemove}
          onCancel={() => setState({ action: '' })}
          title={t('admin.paymentLink.remove')}
          message={t('admin.paymentLink.removeTip')}
          loading={state.loading}
        />
      )}
      {state.action === 'toggleSkipPaymentMethod' && (
        <ConfirmDialog
          onConfirm={onToggleSkipPaymentMethod}
          onCancel={() => setState({ action: '' })}
          title={
            (data.metadata as Record<string, any>)?.allow_skip_payment_method === 'true'
              ? t('admin.paymentLink.disableSkipPaymentMethod')
              : t('admin.paymentLink.enableSkipPaymentMethod')
          }
          message={
            (data.metadata as Record<string, any>)?.allow_skip_payment_method === 'true'
              ? t('admin.paymentLink.disableSkipPaymentMethodTip')
              : t('admin.paymentLink.enableSkipPaymentMethodTip')
          }
          loading={state.loading}
        />
      )}
      {state.action === 'togglePromotionCodes' && (
        <ConfirmDialog
          onConfirm={onTogglePromotionCodes}
          onCancel={() => setState({ action: '' })}
          title={
            data.allow_promotion_codes
              ? t('admin.paymentLink.disablePromotionCodes')
              : t('admin.paymentLink.enablePromotionCodes')
          }
          message={
            data.allow_promotion_codes
              ? t('admin.paymentLink.disablePromotionCodesTip')
              : t('admin.paymentLink.enablePromotionCodesTip')
          }
          loading={state.loading}
        />
      )}
    </ClickBoundary>
  );
}
