'use client';
import { Suspense, type ReactNode } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter, useSearchParams } from 'next/navigation';
import { useSnackbar } from 'notistack';
import { Box, Divider, Skeleton, Stack, Typography } from '@mui/material';
import {
  AppButton,
  AppIcon,
  AppIconButton,
  AppLoading,
  ErrorState,
  EscrowExplainer,
  Money,
  StatusTimeline,
  SurfaceCard,
  type TimelineNode,
} from '@/components';
import { bookingInvoicePath, ROUTES } from '@/constants';
import { formatShamsiDateTime } from '@/utils';
import { useCheckoutSummary, usePaymentOutcome } from '@/services/payment';
import { CHECKOUT_QUERY_BOOKING_ID, CHECKOUT_QUERY_REQUEST_ID } from '@/services/payment/constants';
import { useBnplOrder } from '@/services/bnpl';
import {
  BNPL_QUERY_PROVIDER,
  CHECKOUT_METHOD_BNPL,
  CHECKOUT_QUERY_METHOD,
} from '@/services/bnpl/constants';

/**
 * Post-payment confirmation — a screenshot-worthy receipt (Iranian users screenshot payment receipts): the
 * paid total, a copyable LTR کد پیگیری, the Shamsi payment date-time, the payment method, the booking
 * reference, the escrow reassurance, and a "what happens next" 2-step strip. The booking is now
 * **confirmed** (flipped by cache invalidation on the return surface, never a blanket refetch). Reused by
 * both the f9 card flow and the f11 BNPL branch: reached with `?method=bnpl` it reads the settled BNPL
 * order instead of the payment outcome for the tracking reference + paid-at timestamp. Real loading/error
 * states — a failed fetch must never silently erase the paid amount.
 */
export default function CheckoutConfirmationPage() {
  return (
    <Suspense fallback={<AppLoading />}>
      <ConfirmationScreen />
    </Suspense>
  );
}

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

  const requestId = Number(params.get(CHECKOUT_QUERY_REQUEST_ID));
  const validRequestId = Number.isInteger(requestId) && requestId > 0;
  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,
    isLoading,
    isError,
    refetch,
  } = useCheckoutSummary(validRequestId ? requestId : undefined);

  // The receipt reference/timestamp come from whichever leg actually settled this request — the card
  // outcome or the BNPL order — never fabricated when the real path hasn't served them yet (REQ-046).
  const outcomeQuery = usePaymentOutcome(validRequestId && !isBnpl ? requestId : undefined);
  const orderQuery = useBnplOrder(validRequestId && isBnpl ? requestId : undefined);

  const trackingCode = isBnpl
    ? (orderQuery.data?.id != null ? String(orderQuery.data.id) : null)
    : (outcomeQuery.data?.trackingCode ?? null);
  const paidAt = isBnpl ? (orderQuery.data?.settledAt ?? null) : (outcomeQuery.data?.paidAt ?? null);
  const methodLabel = isBnpl
    ? t('method_bnpl_provider', { provider: bnplProvider ? tBnpl(`provider_${bnplProvider}`) : tBnpl('installments_heading') })
    : t('method_card');

  const nextStepsNodes: TimelineNode[] = [
    { key: 'nurse_notified', label: t('next_step_nurse_notified'), state: 'completed' },
    { key: 'visit_checkin', label: t('next_step_visit_checkin'), state: 'pending' },
  ];

  const handleCopy = () => {
    if (!trackingCode) return;
    navigator.clipboard.writeText(trackingCode).then(() => {
      enqueueSnackbar(t('tracking_code_copied'), { variant: 'success' });
    });
  };

  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>

      {isLoading ? (
        <ReceiptSkeleton />
      ) : isError || !summary ? (
        <ErrorState message={t('error_body')} retryLabel={tc('retry')} onRetry={() => refetch()} />
      ) : (
        <SurfaceCard sx={{ width: '100%' }}>
          <Stack sx={{ gap: 1.5, alignItems: 'center' }}>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {t('total_paid_label')}
            </Typography>
            <Money amountIrr={summary.totalIrr} tone="emphasis" size="xl" sx={{ fontWeight: 800 }} />
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {summary.variantLabel} · {summary.nurseName}
            </Typography>

            <Divider sx={{ width: '100%', my: 0.5 }} />

            <Stack sx={{ width: '100%', gap: 1 }}>
              {trackingCode ? (
                <ReceiptRow label={t('receipt_tracking_code_label')}>
                  <Stack direction="row" sx={{ alignItems: 'center', gap: 0.5 }}>
                    <Box component="span" dir="ltr" sx={{ fontWeight: 700 }}>
                      {trackingCode}
                    </Box>
                    <AppIconButton icon="copy" size="small" title={t('copy_tracking_code')} onClick={handleCopy} />
                  </Stack>
                </ReceiptRow>
              ) : null}
              {paidAt ? (
                <ReceiptRow label={t('receipt_paid_at_label')} value={formatShamsiDateTime(paidAt, locale)} />
              ) : null}
              <ReceiptRow label={t('receipt_method_label')} value={methodLabel} />
              {bookingId != null ? (
                <ReceiptRow label={t('receipt_booking_ref_label')}>
                  <Box component="span" dir="ltr" sx={{ fontWeight: 700 }}>
                    {bookingId}
                  </Box>
                </ReceiptRow>
              ) : null}
            </Stack>
          </Stack>
        </SurfaceCard>
      )}

      <Stack sx={{ width: '100%' }}>
        <EscrowExplainer />
      </Stack>

      <SurfaceCard sx={{ width: '100%' }}>
        <Stack sx={{ gap: 1.5 }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
            {t('next_steps_title')}
          </Typography>
          <StatusTimeline nodes={nextStepsNodes} />
        </Stack>
      </SurfaceCard>

      <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>
  );
}

function ReceiptRow({ label, value, children }: { label: string; value?: string; children?: ReactNode }) {
  return (
    <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center', gap: 2 }}>
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {label}
      </Typography>
      {children ?? (
        <Typography variant="body2" sx={{ fontWeight: 700 }}>
          {value}
        </Typography>
      )}
    </Stack>
  );
}

function ReceiptSkeleton() {
  return (
    <Stack sx={{ gap: 1.5, width: '100%' }}>
      <Skeleton variant="text" width="40%" height={24} sx={{ mx: 'auto' }} />
      <Skeleton variant="text" width="60%" height={48} sx={{ mx: 'auto' }} />
      <Skeleton variant="rounded" height={140} />
    </Stack>
  );
}
