import { Divider, Stack, Typography } from '@mui/material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  useSessionContext,
  usePaymentMethodContext,
  useSubmitFeature,
  useCustomerFormFeature,
} from '@blocklet/payment-react-headless';
import StripeForm from '../../../payment/form/stripe';
import ConfirmDialog from '../../../components/confirm';
import PriceChangeConfirm from '../../../components/price-change-confirm';
import ServiceSuspendedDialog from '../../../components/service-suspended-dialog';
import { formatTokenAmount } from '../../utils/format';

function getRedirectUrl(session: any): string | undefined {
  try {
    const params = new URLSearchParams(window.location.search);
    const redirect = params.get('redirect');
    if (redirect) return decodeURIComponent(redirect);
  } catch {
    // ignore
  }
  if (session?.success_url) return session.success_url;
  if (session?.payment_link?.after_completion?.redirect?.url) {
    return session.payment_link.after_completion.redirect.url;
  }
  return undefined;
}

export default function CheckoutDialogs() {
  const { t } = useLocaleContext();
  const { session } = useSessionContext();
  const { currency, stripe } = usePaymentMethodContext();
  const submit = useSubmitFeature();
  const form = useCustomerFormFeature();
  const mode = session?.mode || 'payment';

  // Stripe dialog
  const stripeContext = submit.context?.type === 'stripe' ? submit.context : null;
  const showStripeDialog = submit.status === 'waiting_stripe' && stripeContext?.clientSecret;

  return (
    <>
      {/* Stripe Payment Dialog */}
      {showStripeDialog && (
        <StripeForm
          clientSecret={stripeContext!.clientSecret}
          intentType={stripeContext!.intentType || 'payment_intent'}
          publicKey={stripe?.publishableKey || ''}
          mode={mode}
          customer={
            {
              name: form.values.customer_name,
              email: form.values.customer_email,
              phone: form.values.customer_phone,
              address: form.values.billing_address,
            } as any
          }
          returnUrl={getRedirectUrl(session)}
          onConfirm={submit.stripeConfirm}
          onCancel={submit.stripeCancel}
          onSkip={
            stripeContext!.noPaymentRequired &&
            `${(session?.metadata as Record<string, any>)?.allow_skip_payment_method}` === 'true'
              ? submit.stripeSkip
              : undefined
          }
        />
      )}

      {/* Price Change Confirmation Dialog — reuse V1's PriceChangeConfirm component */}
      {submit.status === 'confirming_price' && submit.context?.type === 'price_change' && (
        <PriceChangeConfirm
          open
          changePercent={submit.context.changePercent}
          onConfirm={submit.confirm}
          onCancel={submit.cancel}
          loading={false}
        />
      )}

      {/* Fast Pay Confirmation Dialog */}
      {submit.status === 'confirming_fast_pay' && submit.context?.type === 'fast_pay' && (
        <ConfirmDialog
          onConfirm={submit.confirm}
          onCancel={submit.cancel}
          title={
            submit.context.payType === 'credit'
              ? t('payment.checkout.fastPay.credit.title')
              : t('payment.checkout.fastPay.title')
          }
          message={
            submit.context.payType === 'credit' ? (
              <Typography>
                {t('payment.checkout.fastPay.credit.meteringSubscriptionMessage', {
                  available: `${formatTokenAmount(submit.context.amount || '0', currency)} ${currency?.symbol || ''}`,
                })}
              </Typography>
            ) : (
              <Stack>
                <Typography>{t('payment.checkout.fastPay.autoPaymentReason')}</Typography>
                <Divider sx={{ mt: 1.5, mb: 1.5 }} />
                <Stack spacing={1}>
                  <Stack sx={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Typography sx={{ color: 'text.primary', whiteSpace: 'nowrap' }}>
                      {t('payment.checkout.fastPay.payer')}
                    </Typography>
                    <Typography sx={{ color: 'text.secondary', fontSize: 14 }}>
                      {submit.context.payer
                        ? `${submit.context.payer.slice(0, 10)}...${submit.context.payer.slice(-6)}`
                        : ''}
                    </Typography>
                  </Stack>
                  <Stack sx={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Typography sx={{ color: 'text.primary' }}>{t('payment.checkout.fastPay.amount')}</Typography>
                    <Typography>
                      {formatTokenAmount(submit.context.amount || '0', currency)} {currency?.symbol || ''}
                    </Typography>
                  </Stack>
                </Stack>
              </Stack>
            )
          }
          loading={false}
          color="primary"
        />
      )}

      {/* Service Suspended Dialog */}
      {(submit.context as any)?.type === 'service_suspended' && <ServiceSuspendedDialog open onClose={submit.cancel} />}

      {/* Credit Insufficient Dialog (matches V1 ConfirmDialog) */}
      {submit.status === 'credit_insufficient' && submit.context?.type === 'credit_insufficient' && (
        <ConfirmDialog
          onConfirm={submit.cancel}
          onCancel={submit.cancel}
          title={t('payment.checkout.fastPay.credit.insufficientTitle')}
          message={<Typography>{t('payment.checkout.fastPay.credit.insufficientMessage')}</Typography>}
          confirm={t('common.confirm')}
        />
      )}
    </>
  );
}
