import { CheckoutV2 } from '@blocklet/payment-react';
import { useSearchParams } from 'react-router-dom';

type Props = {
  id: string;
};

export default function Payment({ id }: Props) {
  const [searchParams] = useSearchParams();
  const redirect = searchParams.get('redirect');
  const onPaid = (data: any) => {
    if (data?.checkoutSession?.success_url) {
      setTimeout(() => {
        const tmp = new URL(data.checkoutSession.success_url as string, window.location.origin);
        tmp.searchParams.set('checkout_session_id', data.checkoutSession.id);
        window.location.replace(tmp.href);
      }, 1000);
      return;
    }
    if (data?.paymentLink) {
      if (data.paymentLink.after_completion?.type === 'redirect' && data.paymentLink.after_completion?.redirect?.url) {
        setTimeout(() => {
          const tmp = new URL(data.paymentLink?.after_completion?.redirect?.url as string, window.location.origin);
          tmp.searchParams.set('checkout_session_id', data.checkoutSession.id);
          window.location.replace(tmp.href);
        }, 1000);
        return;
      }
    }
    if (redirect) {
      setTimeout(() => {
        window.location.replace(redirect);
      }, 1000);
    }
  };

  return <CheckoutV2 mode="standalone" id={id} onPaid={onPaid} />;
}
