'use client';
import { Suspense } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter, useSearchParams } from 'next/navigation';
import { Stack } from '@mui/material';
import { AppButton, AppLoading, EmptyState } from '@/components';
import { ROUTES } from '@/constants';
import {
  BNPL_QUERY_OUTCOME,
  BNPL_QUERY_PLAN,
  BNPL_QUERY_PROVIDER,
  BNPL_QUERY_REQUEST_ID,
  BNPL_QUERY_TRANSACTION_ID,
} from '@/services/bnpl/constants';
import type { BnplHandoffOutcome, ProviderCode } from '@/services/bnpl/types';

/**
 * Dev provider-handoff harness — a **test harness, not a product feature**. It stands in for the BNPL
 * provider so the initiate → redirect → return round-trip is exercisable without a real provider: the
 * mock's `redirectUrl` points here, and the pay/cancel buttons drive both outcome branches of the return
 * surface (a real provider redirects back after the customer completes or abandons the agreement). On the
 * real path the `redirectUrl` is the provider's absolute URL and this page is never reached.
 */
export default function BnplGatewayPage() {
  return (
    <Suspense fallback={<AppLoading />}>
      <BnplGatewayScreen />
    </Suspense>
  );
}

function BnplGatewayScreen() {
  const t = useTranslations('bnpl');
  const locale = useLocale();
  const router = useRouter();
  const params = useSearchParams();

  const requestId = params.get(BNPL_QUERY_REQUEST_ID) ?? '';
  const transactionId = params.get(BNPL_QUERY_TRANSACTION_ID) ?? '';
  const provider = (params.get(BNPL_QUERY_PROVIDER) ?? '') as ProviderCode | '';
  const providerName = provider ? t(`provider_${provider}`) : t('installments_heading');

  const returnWith = (outcome: BnplHandoffOutcome) => {
    const query = new URLSearchParams({
      [BNPL_QUERY_REQUEST_ID]: requestId,
      [BNPL_QUERY_TRANSACTION_ID]: transactionId,
      [BNPL_QUERY_PROVIDER]: provider,
      [BNPL_QUERY_PLAN]: params.get(BNPL_QUERY_PLAN) ?? '',
      [BNPL_QUERY_OUTCOME]: outcome,
    });
    router.replace(`/${locale}${ROUTES.CHECKOUT_BNPL_RETURN}?${query.toString()}`);
  };

  return (
    <EmptyState
      icon="installments"
      title={t('handoff_title')}
      body={t('handoff_body', { provider: providerName })}
      action={
        <Stack sx={{ gap: 1.5, alignItems: 'center', width: '100%' }}>
          <AppButton color="secondary" variant="contained" size="large" onClick={() => returnWith('success')}>
            {t('handoff_pay_success')}
          </AppButton>
          <AppButton variant="text" color="error" onClick={() => returnWith('failure')}>
            {t('handoff_pay_fail')}
          </AppButton>
        </Stack>
      }
    />
  );
}
