/**
 * PurchaseDetailsQr.tsx - FDS §9.2 Purchase Details + QR Email
 *
 * Contains deal details and the QR PNG as an embedded image (printable).
 * If the purchaser is a guest, includes a magic link for account conversion.
 */

import React from 'react';
import {
  Html,
  Head,
  Body,
  Container,
  Section,
  Text,
  Link,
  Img,
  Hr,
  Preview,
} from '@/server/email/primitives.js';
import { dirForLocale, type Locale } from '@/lib/i18n/index.js';
import { emailAlpha, fonts, spacing, tokens } from '@/server/email/tokens/index.js';
import { formatEmailDateTime } from '@/lib/format';

export interface PurchaseDetailsQrProps {
  dealTitle: string;
  description: string;
  businessName: string;
  address: string;
  hours: string;
  qrPngUrl: string;
  expiryIso: string;
  specialInstructions?: string;
  /** Only provided for guest purchases - magic link for account conversion. */
  magicLinkUrl?: string;
  /**
   * Only provided for guest purchases — signed confirmation URL that lets
   * the guest reopen their receipt without authenticating (BUG-2).
   */
  confirmationUrl?: string;
  locale?: Locale;
}

const copy = {
  he: {
    preview: (title: string) => `קוד QR לשימוש: ${title}`,
    heading: 'פרטי הרכישה שלך',
    subheading: 'הצג קוד זה בעסק לאישור המימוש',
    dealTitle: 'שם העסקה',
    description: 'תיאור',
    businessName: 'שם העסק',
    address: 'כתובת',
    hours: 'שעות פעילות',
    expiry: 'בתוקף עד',
    specialInstructions: 'הוראות מיוחדות',
    qrAlt: 'קוד QR למימוש',
    redeemTitle: 'שלוש דרכים למימוש',
    redeemApp: '1. פתח את האפליקציה → עסקאות שלי → הצג קוד',
    redeemDeal: '2. כנס לדף העסקה ולחץ על "מימוש"',
    redeemEmail: '3. הצג את המייל הזה בעסק - עובד גם בלי טלפון',
    guestTitle: 'החשבון שלך מוכן',
    guestText: 'כל מה שצריך זה להגדיר סיסמה ולשמור את ההיסטוריה שלך.',
    guestCta: 'הפעל את החשבון',
    viewReceiptCta: 'צפה בקבלה',
  },
  en: {
    preview: (title: string) => `Your QR code for: ${title}`,
    heading: 'Your Purchase Details',
    subheading: 'Show this code at the business to redeem',
    dealTitle: 'Deal',
    description: 'Description',
    businessName: 'Business',
    address: 'Address',
    hours: 'Hours',
    expiry: 'Valid Until',
    specialInstructions: 'Special Instructions',
    qrAlt: 'QR Code for redemption',
    redeemTitle: 'Three ways to redeem',
    redeemApp: '1. Open the app → My Deals → Show code',
    redeemDeal: '2. Go to the deal page and tap "Redeem"',
    redeemEmail: '3. Show this email at the business - works without a phone',
    guestTitle: 'Your account is ready',
    guestText: 'Just set a password to save your purchase history.',
    guestCta: 'Activate my account',
    viewReceiptCta: 'View receipt',
  },
} as const;

export default function PurchaseDetailsQr({
  dealTitle,
  description,
  businessName,
  address,
  hours,
  qrPngUrl,
  expiryIso,
  specialInstructions,
  magicLinkUrl,
  confirmationUrl,
  locale = 'he',
}: PurchaseDetailsQrProps) {
  const t = copy[locale];
  const dir = dirForLocale(locale);
  const fontFamily = locale === 'he' ? fonts.he : fonts.en;

  const containerStyle: React.CSSProperties = {
    maxWidth: spacing.cardMaxMedium,
    margin: '0 auto',
    backgroundColor: tokens.surfaceBase,
    borderRadius: '8px',
    border: `1px solid ${tokens.borderDefault}`,
    overflow: 'hidden',
  };

  const headerStyle: React.CSSProperties = {
    backgroundColor: tokens.brandPrimary700,
    padding: spacing.padSectionLg,
    textAlign: locale === 'he' ? 'right' : 'left',
  };

  const sectionStyle: React.CSSProperties = {
    padding: spacing.padHeaderWide,
    direction: dir,
    textAlign: locale === 'he' ? 'right' : 'left',
  };

  const labelStyle: React.CSSProperties = {
    fontSize: spacing.px11,
    color: tokens.textMuted,
    fontFamily,
    textTransform: 'uppercase',
    letterSpacing: '0.05em',
    marginBottom: '2px',
    marginTop: spacing.px16,
  };

  const valueStyle: React.CSSProperties = {
    fontSize: spacing.px15,
    color: tokens.textPrimary,
    fontFamily,
    margin: '0',
  };

  return (
    <Html lang={locale} dir={dir}>
      <Head />
      <Preview>{t.preview(dealTitle)}</Preview>
      <Body style={{ backgroundColor: tokens.neutral100, fontFamily }}>
        <Container style={{ padding: spacing.padPage }}>
          <div style={containerStyle}>
            {/* Header */}
            <Section style={headerStyle}>
              <Text
                style={{
                  fontSize: spacing.px22,
                  fontWeight: 700,
                  color: tokens.brandOnPrimary,
                  fontFamily,
                  margin: '0',
                }}
              >
                {t.heading}
              </Text>
              <Text
                style={{
                  fontSize: spacing.px14,
                  color: emailAlpha.onPrimary80,
                  fontFamily,
                  margin: '6px 0 0',
                }}
              >
                {t.subheading}
              </Text>
            </Section>

            {/* QR Code - centred, printable */}
            <Section
              style={{
                padding: spacing.padSectionLg,
                textAlign: 'center',
                backgroundColor: tokens.neutral50,
              }}
            >
              <Img
                src={qrPngUrl}
                width={200}
                height={200}
                alt={t.qrAlt}
                style={{
                  display: 'block',
                  margin: '0 auto',
                  border: `4px solid ${tokens.neutral200}`,
                  borderRadius: '8px',
                }}
              />
            </Section>

            {/* Deal details */}
            <Section style={sectionStyle}>
              <Text style={labelStyle}>{t.dealTitle}</Text>
              <Text style={{ ...valueStyle, fontSize: spacing.px18, fontWeight: 600 }}>
                {dealTitle}
              </Text>

              {description ? (
                <>
                  <Text style={labelStyle}>{t.description}</Text>
                  <Text style={valueStyle}>{description}</Text>
                </>
              ) : null}

              <Hr style={{ borderColor: tokens.borderDefault, margin: spacing.marginBlock16 }} />

              <Text style={labelStyle}>{t.businessName}</Text>
              <Text style={valueStyle}>{businessName}</Text>

              <Text style={labelStyle}>{t.address}</Text>
              <Text style={valueStyle}>{address}</Text>

              <Text style={labelStyle}>{t.hours}</Text>
              <Text style={valueStyle}>{hours}</Text>

              <Hr style={{ borderColor: tokens.borderDefault, margin: spacing.marginBlock16 }} />

              <Text style={labelStyle}>{t.expiry}</Text>
              <Text
                style={{
                  ...valueStyle,
                  color: tokens.warning600,
                  fontWeight: 600,
                }}
              >
                {formatEmailDateTime(expiryIso, locale)}
              </Text>

              {specialInstructions ? (
                <>
                  <Text style={labelStyle}>{t.specialInstructions}</Text>
                  <Text
                    style={{
                      ...valueStyle,
                      backgroundColor: tokens.neutral100,
                      padding: spacing.px12,
                      borderRadius: '6px',
                      borderRight:
                        locale === 'he' ? `3px solid ${tokens.brandPrimary600}` : undefined,
                      borderLeft:
                        locale !== 'he' ? `3px solid ${tokens.brandPrimary600}` : undefined,
                    }}
                  >
                    {specialInstructions}
                  </Text>
                </>
              ) : null}
            </Section>

            {/* Redemption instructions */}
            <Section
              style={{
                padding: spacing.padHeaderWide,
                backgroundColor: tokens.neutral50,
                borderTop: `1px solid ${tokens.borderDefault}`,
                direction: dir,
                textAlign: locale === 'he' ? 'right' : 'left',
              }}
            >
              <Text
                style={{
                  fontSize: spacing.px14,
                  fontWeight: 600,
                  color: tokens.textSecondary,
                  fontFamily,
                  marginBottom: '8px',
                }}
              >
                {t.redeemTitle}
              </Text>
              {[t.redeemApp, t.redeemDeal, t.redeemEmail].map((line) => (
                <Text
                  key={line}
                  style={{
                    fontSize: spacing.px13,
                    color: tokens.textMuted,
                    fontFamily,
                    margin: '4px 0',
                  }}
                >
                  {line}
                </Text>
              ))}
            </Section>

            {/* Guest receipt link — reopen the confirmation page without login (BUG-2). */}
            {confirmationUrl ? (
              <Section
                style={{
                  padding: spacing.padFooter,
                  direction: dir,
                  textAlign: locale === 'he' ? 'right' : 'left',
                }}
              >
                <Link
                  href={confirmationUrl}
                  style={{
                    color: tokens.brandPrimary600,
                    fontFamily,
                    fontSize: spacing.px14,
                    fontWeight: 600,
                    textDecoration: 'underline',
                  }}
                >
                  {t.viewReceiptCta}
                </Link>
              </Section>
            ) : null}

            {/* Guest magic link */}
            {magicLinkUrl ? (
              <Section
                style={{
                  padding: spacing.padHeaderWide,
                  backgroundColor: tokens.brandPrimary900,
                  direction: dir,
                  textAlign: locale === 'he' ? 'right' : 'left',
                }}
              >
                <Text
                  style={{
                    fontSize: spacing.px16,
                    fontWeight: 600,
                    color: tokens.brandOnPrimary,
                    fontFamily,
                    margin: '0 0 8px',
                  }}
                >
                  {t.guestTitle}
                </Text>
                <Text
                  style={{
                    fontSize: spacing.px14,
                    color: emailAlpha.onPrimary75,
                    fontFamily,
                    margin: spacing.marginBottom16,
                  }}
                >
                  {t.guestText}
                </Text>
                <Link
                  href={magicLinkUrl}
                  style={{
                    backgroundColor: tokens.brandPrimary600,
                    color: tokens.brandOnPrimary,
                    padding: spacing.padStack,
                    borderRadius: '6px',
                    fontFamily,
                    fontSize: spacing.px15,
                    fontWeight: 600,
                    textDecoration: 'none',
                    display: 'inline-block',
                  }}
                >
                  {t.guestCta}
                </Link>
              </Section>
            ) : null}
          </div>
        </Container>
      </Body>
    </Html>
  );
}
