/**
 * PurchaseDetail - per-purchase detail screen (FDS §4.8).
 *
 * Shows deal summary, redemption status, and QR code access.
 * Receives enriched data server-side from the Astro page shell.
 */

'use client';

import { useT } from '@/lib/i18n/react';
import { useLocale } from '@/lib/i18n/react';
import type { Locale } from '@/lib/i18n';
import { HydratedIsland } from '@/components/HydratedIsland';
import { formatCurrency, formatDate } from '@/lib/format';
import { enumLabel } from '@/lib/enums/define-enum';
import { AppShell } from '@/components/ui/layout/AppShell';
import { TopBar } from '@/components/ui/layout/TopBar';
import { BottomNav, useCustomerNavItems } from '@/components/ui/layout/BottomNav';
import { DesktopTopBar, useCustomerDesktopNavItems } from '@/components/ui/layout/DesktopTopBar';
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 { Pill } from '@/components/ui/primitives/Pill';
import { Icon } from '@/components/ui/icons/Icon';
import { IconButton } from '@/components/ui/primitives/IconButton';
import { MDLogo } from '@/components/ui/icons/MDLogo';
import { CustomerDesktopEnd } from '@/components/ui/layout/CustomerDesktopEnd';
import { HamburgerDrawer } from '@/components/ui/layout/HamburgerDrawer';
import { CartNavButton } from '@/components/ui/domain/cart/CartNavButton';
import { GlobalCartDrawer } from '@/components/ui/domain/cart/GlobalCartDrawer';
import { type RedemptionStatus } from '@/lib/enums/redemption-status';

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

export type { RedemptionStatus };

export interface PurchaseDetailProps {
  purchaseId: string;
  dealId: string;
  dealTitle: string;
  vendorName: string;
  /** Numeric string, e.g. "45.00". */
  amountPaid: string;
  quantity: number;
  redemptionStatus: RedemptionStatus;
  /** ISO string - when the QR expires. */
  expiresAt?: string;
  /** ISO string - when the QR was redeemed. */
  redeemedAt?: string;
  /** ISO string - when the purchase was made. */
  createdAt: string;
  /** COUPON | ITEM | GROUP — controls which status vocabulary is shown. */
  dealType?: 'COUPON' | 'ITEM' | 'GROUP';
  /** Payment status — used for refunded badge. */
  paymentStatus?: string;
  isAdmin?: boolean;
  /**
   * Server-resolved locale from Astro frontmatter. Seeds LocaleProvider so SSR
   * and first hydration render use the same locale dictionary as the page
   * shell — prevents React #418 hydration mismatch when the user's cookie
   * locale differs from the store default ('he').
   */
  locale?: Locale;
}

// ─── Status helpers ───────────────────────────────────────────────────────────

function statusTone(status: RedemptionStatus): 'success' | 'danger' | 'info' | 'neutral' {
  switch (status) {
    case 'UNREDEEMED':
      return 'info';
    case 'REDEEMED':
      return 'success';
    case 'EXPIRED':
      return 'danger';
    case 'CANCELLED':
      return 'neutral';
  }
}

// ─── Inner component ──────────────────────────────────────────────────────────

export function PurchaseDetailInner({
  purchaseId,
  dealTitle,
  vendorName,
  amountPaid,
  quantity,
  redemptionStatus,
  expiresAt,
  redeemedAt,
  createdAt,
  dealType = 'COUPON',
  paymentStatus,
  isAdmin = false,
}: Omit<PurchaseDetailProps, 'locale'>) {
  const t = useT('purchase_detail');
  const tCommon = useT('common');
  const tNav = useT('nav');
  const { locale } = useLocale();

  const navItems = useCustomerNavItems('/purchases');
  const desktopNavItems = useCustomerDesktopNavItems('/purchases', { isGuest: false });

  const statusLabel = enumLabel('purchase_status', redemptionStatus, locale, 'customer');

  const showRedemptionPill = dealType === 'COUPON' || dealType === 'GROUP';
  const canShowQr = redemptionStatus === 'UNREDEEMED' && showRedemptionPill;
  const showRefundedPill = paymentStatus === 'REFUNDED';

  return (
    <AppShell
      mode="customer"
      desktopTopBar={
        <DesktopTopBar
          items={desktopNavItems}
          mode="customer"
          logoSlot={<MDLogo className="text-text-inverse" size={28} />}
          endSlot={<CustomerDesktopEnd isAdmin={isAdmin} extra={<CartNavButton />} />}
        />
      }
      topBar={
        <TopBar
          variant="customer"
          title={t('title')}
          startSlot={
            <div className="flex items-center gap-1">
              <HamburgerDrawer isGuest={false} currentPath="/purchases" />
              <IconButton
                variant="on-brand"
                size="md"
                aria-label={tCommon('back')}
                onClick={() => {
                  if (window.history.length > 1) {
                    window.history.back();
                  } else {
                    window.location.href = '/purchases';
                  }
                }}
              >
                <Icon name="ChevronRight" size="md" mirror />
              </IconButton>
            </div>
          }
          endSlot={<CartNavButton />}
        />
      }
      bottomNav={<BottomNav mode="customer" items={navItems} />}
      pageOverlays={<GlobalCartDrawer />}
    >
      <div className="py-6">
        <Breadcrumb
          items={[
            { label: tNav('home'), href: '/' },
            { label: tNav('purchases'), href: '/purchases' },
            { label: dealTitle },
          ]}
        />
        <Container maxWidth="sm" px="4">
          <Stack gap="5">
            {/* ── Status pill ──────────────────────────────────────────── */}
            <div className="flex flex-wrap items-center justify-between gap-2">
              <h1 className="text-text-primary text-[length:var(--font-size-display)] leading-tight font-[var(--font-weight-extrabold)]">
                {dealTitle}
              </h1>
              <div className="flex flex-wrap items-center gap-2">
                {showRefundedPill && (
                  <Pill tone="neutral" size="sm">
                    {t('payment_refunded')}
                  </Pill>
                )}
                {showRedemptionPill && (
                  <Pill tone={statusTone(redemptionStatus)} size="sm">
                    {statusLabel}
                  </Pill>
                )}
              </div>
            </div>

            {redemptionStatus === 'EXPIRED' && (
              <p className="text-text-muted text-sm">{t('expired_helper')}</p>
            )}

            {/* ── Details card ─────────────────────────────────────────── */}
            <div className="bg-surface-raised divide-border-subtle divide-y rounded-xl shadow-md">
              {/* Vendor */}
              <div className="flex items-center justify-between px-4 py-3">
                <span className="text-text-secondary text-sm">{t('vendor')}</span>
                <span className="text-text-primary text-sm font-medium">{vendorName}</span>
              </div>

              {/* Amount paid */}
              <div className="flex items-center justify-between px-4 py-3">
                <span className="text-text-secondary text-sm">{t('amount_paid')}</span>
                <span className="text-brand-primary-700 text-sm font-bold">
                  {formatCurrency(parseFloat(amountPaid) || 0, locale)}
                </span>
              </div>

              {/* Quantity (only if > 1) */}
              {quantity > 1 && (
                <div className="flex items-center justify-between px-4 py-3">
                  <span className="text-text-secondary text-sm">{t('quantity')}</span>
                  <span className="text-text-primary text-sm font-medium">
                    {quantity} {t('units')}
                  </span>
                </div>
              )}

              {/* Purchase date */}
              <div className="flex items-center justify-between px-4 py-3">
                <span className="text-text-secondary text-sm">{t('date')}</span>
                <span className="text-text-primary text-sm font-medium">
                  {formatDate(createdAt, locale)}
                </span>
              </div>

              {/* Valid until (if unredeemed and has expiry) */}
              {redemptionStatus === 'UNREDEEMED' && expiresAt && (
                <div className="flex items-center justify-between px-4 py-3">
                  <span className="text-text-secondary text-sm">{t('valid_until')}</span>
                  <span className="text-text-primary text-sm font-medium">
                    {formatDate(expiresAt, locale)}
                  </span>
                </div>
              )}

              {/* Redeemed at */}
              {redemptionStatus === 'REDEEMED' && redeemedAt && (
                <div className="flex items-center justify-between px-4 py-3">
                  <span className="text-text-secondary text-sm">{t('status_redeemed')}</span>
                  <span className="text-text-primary text-sm font-medium">
                    {formatDate(redeemedAt, locale)}
                  </span>
                </div>
              )}
            </div>

            {/* ── QR action ────────────────────────────────────────────── */}
            {canShowQr && (
              <Button
                variant="primary"
                size="lg"
                iconStart={<Icon name="QrCode" size="sm" />}
                onClick={() => {
                  window.location.href = `/purchases/${purchaseId}/qr`;
                }}
                className="w-full"
              >
                {t('show_qr')}
              </Button>
            )}

            {/* ── Back to purchases ────────────────────────────────────── */}
            <Button
              variant="ghost"
              size="md"
              iconStart={<Icon name="ArrowRight" size="sm" mirror />}
              onClick={() => {
                window.location.href = '/purchases';
              }}
              className="w-full"
            >
              {t('back')}
            </Button>
          </Stack>
        </Container>
      </div>
    </AppShell>
  );
}

// ─── Exported component ───────────────────────────────────────────────────────

/**
 * PurchaseDetail - exported island component.
 *
 * Self-wraps with HydratedIsland (QueryClientProvider + LocaleProvider +
 * ErrorBoundary) so descendants — including AppShell's QueryProgress and
 * GlobalCartDrawer — always run inside a QueryClient + Locale context.
 *
 * `locale` (server-resolved) seeds LocaleProvider so SSR and first hydration
 * render use the same dictionary, preventing React #418 hydration mismatch.
 */
export function PurchaseDetail({ locale, ...props }: PurchaseDetailProps) {
  return (
    <HydratedIsland locale={locale}>
      <PurchaseDetailInner {...props} />
    </HydratedIsland>
  );
}
