'use client';
import { Suspense } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter, useSearchParams } from 'next/navigation';
import { Paper, Stack, Typography } from '@mui/material';
import { AppButton, AppIcon, AppLoading, Money } from '@/components';
import { bookingInvoicePath, ROUTES } from '@/constants';
import { useCheckoutSummary } from '@/services/payment';
import { CHECKOUT_QUERY_BOOKING_ID, CHECKOUT_QUERY_REQUEST_ID } from '@/services/payment/constants';
import {
  BNPL_QUERY_PROVIDER,
  CHECKOUT_METHOD_BNPL,
  CHECKOUT_QUERY_METHOD,
} from '@/services/bnpl/constants';

/**
 * Post-payment confirmation — the booking is now **confirmed** (flipped by cache invalidation on the
 * return surface, never a blanket refetch). Links back to the f8 booking detail («مشاهده رزرو») and to
 * the invoice («دانلود فاکتور»). Reused by both the f9 card flow and the f11 BNPL branch: when reached
 * with `?method=bnpl` it also renders a «پرداخت‌شده با اقساط» line (a settled BNPL order is, to
 * Balinyaar, a card payment net-of-fee — there is no separate BNPL confirmation). Without a `booking_id`
 * (REQ-017/024 unmet on the real path) the deep-links fall back to the bookings list.
 */
export default function CheckoutConfirmationPage() {
  return (
    <Suspense fallback={<AppLoading />}>
      <ConfirmationScreen />
    </Suspense>
  );
}

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

  const requestId = Number(params.get(CHECKOUT_QUERY_REQUEST_ID));
  const bookingIdParam = params.get(CHECKOUT_QUERY_BOOKING_ID);
  const bookingId = bookingIdParam ? Number(bookingIdParam) : null;
  const isBnpl = params.get(CHECKOUT_QUERY_METHOD) === CHECKOUT_METHOD_BNPL;
  const bnplProvider = params.get(BNPL_QUERY_PROVIDER) ?? '';

  const { data: summary } = useCheckoutSummary(
    Number.isInteger(requestId) && requestId > 0 ? requestId : undefined,
  );

  return (
    <Stack sx={{ gap: 3, alignItems: 'center', textAlign: 'center' }}>
      <AppIcon icon="verified" size={64} color="var(--bal-success)" />
      <Stack sx={{ gap: 0.5 }}>
        <Typography variant="h6" component="h1">
          {t('confirm_title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('confirm_subtitle')}
        </Typography>
      </Stack>

      {summary ? (
        <Paper
          elevation={0}
          sx={{ p: 2.5, borderRadius: 2, border: '1px solid', borderColor: 'divider', width: '100%' }}
        >
          <Stack sx={{ gap: 0.5, alignItems: 'center' }}>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {t('total_paid_label')}
            </Typography>
            <Money amountIrr={summary.totalIrr} tone="emphasis" size="lg" />
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {summary.variantLabel} · {summary.nurseName}
            </Typography>
            {isBnpl ? (
              <Typography variant="caption" sx={{ color: 'var(--bal-secondary)', fontWeight: 500, mt: 0.5 }}>
                {tBnpl('paid_via_installments', {
                  provider: bnplProvider ? tBnpl(`provider_${bnplProvider}`) : tBnpl('installments_heading'),
                })}
              </Typography>
            ) : null}
          </Stack>
        </Paper>
      ) : null}

      <Stack sx={{ gap: 1, width: '100%' }}>
        <AppButton
          color="primary"
          variant="contained"
          size="large"
          onClick={() =>
            router.push(`/${locale}${bookingId != null ? `${ROUTES.BOOKINGS}/${bookingId}` : ROUTES.BOOKINGS}`)
          }
        >
          {t('view_booking')}
        </AppButton>
        {bookingId != null ? (
          <AppButton
            variant="outlined"
            color="primary"
            startIcon="document"
            onClick={() => router.push(`/${locale}${bookingInvoicePath(bookingId)}`)}
          >
            {t('download_invoice')}
          </AppButton>
        ) : null}
      </Stack>
    </Stack>
  );
}
