/**
 * PurchaseConfirmation - post-checkout success screen (FDS §4.5).
 *
 * Shows confetti reaction, deal summary, QR-sent notice, and action buttons.
 * Guest users also see a soft registration prompt.
 */

'use client';

import { useState } from 'react';
import { useT } from '@/lib/i18n/react';
import { useLocale } from '@/lib/i18n/react';
import { formatDate } from '@/lib/format';
import { interpolate } from '@/lib/i18n/interpolate';
import { cn } from '@/lib/cn';
import { HydratedIsland } from '@/components/HydratedIsland';
import type { Locale } from '@/lib/i18n';
import { AppShell } from '@/components/ui/layout/AppShell';
import { TopBar } from '@/components/ui/layout/TopBar';
import { Container } from '@/components/ui/layout/Container';
import { Stack } from '@/components/ui/layout/Stack';
import { Breadcrumb } from '@/components/ui/layout/Breadcrumb';
import { Button } from '@/components/ui/primitives/Button';
import { Icon } from '@/components/ui/icons/Icon';
import { IconButton } from '@/components/ui/primitives/IconButton';
import { InlineNotice } from '@/components/ui/feedback/InlineNotice';
import { PostPurchaseReaction } from '@/components/ui/domain/PostPurchaseReaction';
import { CartNavButton } from '@/components/ui/domain/cart/CartNavButton';
import { GlobalCartDrawer } from '@/components/ui/domain/cart/GlobalCartDrawer';
import { CheckoutModal } from '@/features/checkout-modal/CheckoutModal';
import { QrCodeCard } from '@/components/ui/domain/QrCodeCard/QrCodeCard';
import { PostPurchaseReview } from '@/features/post-purchase/PostPurchaseReview';
import { RelatedDealsSection } from '@/components/ui/domain/RelatedDealsSection';
import { AnimatedNumber } from '@/components/ui/domain/AnimatedNumber';
import type { RelatedDeals } from '@/server/catalog/related';
import type { RedemptionStatus } from '@/lib/enums/redemption-status';
import { formatAgorotShekels, shekelsToAgorot } from '@/lib/money';
import { usePurchaseMomentTimeline } from './usePurchaseMomentTimeline';

// ─── Types ────────────────────────────────────────────────────────────────────

export interface PurchaseConfirmationProps {
  /** The purchase ID, used to build QR link. */
  purchaseId: string;
  /** Title of the purchased deal. */
  dealTitle: string;
  /** Display name of the vendor / business. */
  businessName: string;
  /** Amount paid as numeric string, e.g. "45.00". */
  amountPaid: string;
  /** True when the buyer checked out as a guest (no session). */
  isGuest: boolean;
  /** Vendor receipt PDF URL (optional — available once charge completes). */
  vendorReceiptUrl?: string | null;
  /** PNG URL for the QR code (optional — available once QR is generated). */
  qrPngUrl?: string;
  /** Units purchased on this line. >1 means multiple per-unit QR codes exist. */
  quantity?: number;
  /** ISO expiry for the redemption QR. */
  expiresAt?: string;
  /** Redemption state — review prompt only after REDEEMED. */
  redemptionStatus?: RedemptionStatus;
  relatedSections?: RelatedDeals;
  vendorName?: string;
  /**
   * Server-resolved locale from Astro frontmatter. Seeds LocaleProvider so SSR
   * and first hydration render use the correct locale.
   */
  locale?: Locale;
}

// ─── Component ────────────────────────────────────────────────────────────────

/**
 * PurchaseConfirmation - full-screen success page shown after checkout.
 */
function PurchaseConfirmationInner({
  purchaseId,
  dealTitle,
  businessName,
  amountPaid,
  isGuest,
  vendorReceiptUrl,
  qrPngUrl,
  quantity = 1,
  expiresAt,
  redemptionStatus = 'UNREDEEMED',
  relatedSections,
  vendorName,
}: Omit<PurchaseConfirmationProps, 'locale'>) {
  const t = useT('confirmation');
  const tPurchaseDetail = useT('purchase_detail');
  const { locale } = useLocale();
  const timeline = usePurchaseMomentTimeline();

  const [reactionDismissed, setReactionDismissed] = useState(false);

  const amountPaidAgorot = shekelsToAgorot(parseFloat(amountPaid) || 0);
  const formattedAmount = formatAgorotShekels(amountPaidAgorot);
  const purchaseRef = purchaseId.slice(0, 8).toUpperCase();
  const showReview = !isGuest && redemptionStatus === 'REDEEMED';
  const showInlineQr = Boolean(qrPngUrl);

  const tCommon = useT('common');
  const tNav = useT('nav');

  return (
    <AppShell
      mode="customer"
      topBar={
        <TopBar
          variant="customer"
          title={t('heading')}
          startSlot={
            <IconButton
              variant="on-brand"
              size="md"
              aria-label={tCommon('back')}
              onClick={() => {
                window.location.href = isGuest ? '/' : '/purchases';
              }}
            >
              <Icon name="ChevronRight" size="md" mirror />
            </IconButton>
          }
          endSlot={<CartNavButton />}
        />
      }
      pageOverlays={
        <>
          <GlobalCartDrawer />
          <CheckoutModal />
        </>
      }
    >
      <div className="py-6">
        <Breadcrumb
          items={[
            { label: tNav('home'), href: '/' },
            { label: tNav('purchases'), href: '/purchases' },
            { label: t('heading') },
          ]}
        />
        <Container maxWidth="sm" px="4">
          <Stack
            gap="5"
            data-testid="purchase-moment-shell"
            data-sequence-phase={timeline.phase}
            data-reduced-motion={timeline.reducedMotion ? 'true' : 'false'}
          >
            {!reactionDismissed && (
              <PostPurchaseReaction
                purchaseCount={1}
                isGuest={isGuest}
                onDismiss={() => setReactionDismissed(true)}
                onRegister={() => {
                  window.location.href = `/register-from-magic-link?purchaseId=${purchaseId}`;
                }}
              />
            )}

            <div
              className="flex flex-col items-center gap-3 text-center"
              data-testid="purchase-moment-hero"
            >
              <span
                className={cn(
                  'flex h-16 w-16 items-center justify-center rounded-full',
                  'bg-success-100 text-success-600',
                )}
                aria-hidden="true"
              >
                <Icon name="Check" size="xl" />
              </span>
              <h1 className="text-text-primary text-[length:var(--font-size-display)] leading-tight font-[var(--font-weight-extrabold)]">
                {t('heading')}
              </h1>
            </div>

            <div
              className={cn(
                'bg-surface-raised rounded-xl px-4 py-4 shadow-md transition-[opacity,transform] duration-[var(--duration-base)] ease-[var(--ease-out)] motion-reduce:transition-none',
                timeline.summaryVisible
                  ? 'translate-y-0 opacity-100'
                  : 'pointer-events-none translate-y-2 opacity-0',
              )}
              data-testid="purchase-moment-summary"
              aria-hidden={!timeline.summaryVisible}
            >
              <Stack gap="2">
                <p className="text-text-primary text-base font-semibold">{dealTitle}</p>
                <p className="text-text-secondary text-sm">
                  {interpolate(t('deal_by'), { businessName })}
                </p>
                <p className="text-text-muted text-xs">
                  {interpolate(t('order_ref'), { ref: purchaseRef })}
                </p>
                <div className="mt-2 flex items-center justify-between">
                  <span className="text-text-secondary text-sm">{t('amount_paid')}</span>
                  <AnimatedNumber
                    value={amountPaidAgorot}
                    formatValue={(value) => formatAgorotShekels(Math.round(value))}
                    className="text-brand-primary-700 text-base font-bold"
                    ariaLabel={t('amount_paid_aria').replace('{{amount}}', formattedAmount)}
                    testId="purchase-confirmation-total"
                    reserveValue={amountPaidAgorot}
                  />
                </div>
              </Stack>
            </div>

            <div
              className={cn(
                'transition-[opacity,transform] duration-[var(--duration-base)] ease-[var(--ease-out)] motion-reduce:transition-none',
                timeline.summaryVisible
                  ? 'translate-y-0 opacity-100'
                  : 'pointer-events-none translate-y-2 opacity-0',
              )}
              data-testid="purchase-moment-notice"
              aria-hidden={!timeline.summaryVisible}
            >
              <InlineNotice
                tone="success"
                title={t('qr_sent_title')}
                description={t('qr_sent_desc')}
              />
            </div>

            <div
              className={cn(
                'transition-[opacity,transform] duration-[var(--duration-slow)] ease-[var(--ease-out)] motion-reduce:transition-none',
                timeline.actionsVisible
                  ? 'translate-y-0 opacity-100'
                  : 'pointer-events-none translate-y-3 opacity-0',
              )}
              data-testid="purchase-moment-actions"
              aria-hidden={!timeline.actionsVisible}
              inert={!timeline.actionsVisible}
            >
              <Stack gap="5">
                {vendorReceiptUrl && (
                  <Button
                    variant="ghost"
                    size="md"
                    iconStart={<Icon name="FileText" size="sm" />}
                    onClick={() => {
                      window.open(vendorReceiptUrl, '_blank', 'noopener,noreferrer');
                    }}
                    className="w-full"
                  >
                    {tPurchaseDetail('download_receipt')}
                  </Button>
                )}

                {isGuest && (
                  <Stack gap="3">
                    <InlineNotice
                      tone="info"
                      title={t('guest_prompt_title')}
                      description={t('guest_prompt_desc')}
                    />
                    <Button
                      variant="ghost"
                      size="md"
                      onClick={() => {
                        window.location.href = `/register-from-magic-link?purchaseId=${purchaseId}`;
                      }}
                      className="w-full"
                    >
                      {t('guest_prompt_cta')}
                    </Button>
                  </Stack>
                )}

                {showInlineQr && (
                  <Stack gap="2">
                    <p className="text-text-primary text-center text-sm font-medium">{dealTitle}</p>
                    {expiresAt && (
                      <p className="text-text-muted text-center text-xs">
                        {tPurchaseDetail('valid_until')} {formatDate(expiresAt, locale)}
                      </p>
                    )}
                    <p className="text-text-secondary text-center text-xs">
                      {quantity > 1
                        ? interpolate(t('qr_multi_caption'), { count: String(quantity) })
                        : t('qr_caption')}
                    </p>
                    <QrCodeCard qrPngUrl={qrPngUrl!} expiryIso={expiresAt} className="w-full" />
                  </Stack>
                )}

                {showReview && <PostPurchaseReview purchaseId={purchaseId} />}

                <Button
                  variant="primary"
                  size="lg"
                  onClick={() => {
                    window.location.href = `/purchases/${purchaseId}/qr`;
                  }}
                  className="w-full"
                >
                  {showInlineQr ? t('view_qr_fullscreen') : t('view_qr')}
                </Button>

                <Button
                  variant="ghost"
                  size="md"
                  iconStart={<Icon name="ArrowRight" size="sm" mirror />}
                  onClick={() => {
                    window.location.href = isGuest ? '/' : '/purchases';
                  }}
                  className="w-full"
                >
                  {t(isGuest ? 'back_to_home' : 'back_to_purchases')}
                </Button>
              </Stack>
            </div>
          </Stack>
        </Container>

        {relatedSections &&
          (relatedSections.alsoBought.length > 0 || relatedSections.moreFromVendor.length > 0) && (
            <div className="mt-8">
              <RelatedDealsSection
                alsoBought={relatedSections.alsoBought}
                similar={[]}
                moreFromVendor={relatedSections.moreFromVendor}
                vendorName={vendorName}
              />
            </div>
          )}
      </div>
    </AppShell>
  );
}

export function PurchaseConfirmation({ locale, ...props }: PurchaseConfirmationProps) {
  return (
    <HydratedIsland locale={locale}>
      <PurchaseConfirmationInner {...props} />
    </HydratedIsland>
  );
}
