import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';

const colors = {
  primary: '#E11D48',
  primaryDark: '#BE123C',
  primaryLight: '#FFE4E6',
  secondary: '#64748B',
  success: '#0EA5E9',
  successLight: '#E0F2FE',
  warning: '#F59E0B',
  error: '#7F1D1D',
  background: '#F8FAFC',
  white: '#FFFFFF',
  border: '#E2E8F0',
  borderLight: '#F1F5F9',
  text: '#0F172A',
  textLight: '#64748B',
  textDark: '#020617',
  purple: '#7C3AED',
  purpleLight: '#EDE9FE',
  accent: '#FFF1F2',
};

// Company Info — update these as needed
const COMPANY = {
  name: 'OutreachExpert',
  tagline: 'Premium Guest Posting Service',
  email: 'support@outreachexpert.com',
  phone: '+1 (555) 123-4567',
  website: 'www.outreachexpert.com',
  address: '123 Business Ave, Suite 400',
  city: 'New York, NY 10001',
  country: 'United States',
  taxId: 'TAX-ID: US-8839201',
};

const styles = StyleSheet.create({
  page: {
    padding: 0,
    fontSize: 10,
    fontFamily: 'Helvetica',
    backgroundColor: colors.white,
  },

  // ── Top accent bar ──
  topBar: {
    height: 5,
    backgroundColor: colors.primary,
  },

  // ── Content wrapper with consistent margins ──
  content: {
    paddingHorizontal: 36,
    paddingTop: 28,
    paddingBottom: 70, // space for fixed footer
  },

  // ── Header ──
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 24,
  },
  companyBlock: {
    flexDirection: 'column',
  },
  logo: {
    fontSize: 22,
    fontFamily: 'Helvetica-Bold',
    color: colors.primary,
    letterSpacing: 0.5,
    marginBottom: 2,
  },
  tagline: {
    fontSize: 8,
    color: colors.textLight,
    marginBottom: 6,
  },
  companyMeta: {
    fontSize: 7.5,
    color: colors.textLight,
    marginBottom: 1.5,
  },

  invoiceBadge: {
    alignItems: 'flex-end',
  },
  invoiceLabel: {
    fontSize: 28,
    fontFamily: 'Helvetica-Bold',
    color: colors.primary,
    letterSpacing: 2,
    marginBottom: 4,
  },
  invoiceNumberRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  invoiceNumberLabel: {
    fontSize: 8,
    color: colors.textLight,
    marginRight: 4,
  },
  invoiceNumberValue: {
    fontSize: 8,
    fontFamily: 'Helvetica-Bold',
    color: colors.text,
  },

  // ── Divider ──
  divider: {
    height: 1,
    backgroundColor: colors.border,
    marginBottom: 20,
  },
  dividerAccent: {
    height: 2,
    backgroundColor: colors.primary,
    marginBottom: 20,
  },

  // ── Info Cards Grid ──
  infoCardsGrid: {
    flexDirection: 'row',
    gap: 10,
    marginBottom: 22,
  },
  infoCard: {
    flex: 1,
    backgroundColor: colors.background,
    padding: 12,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: colors.border,
  },
  cardTitle: {
    fontSize: 7,
    fontFamily: 'Helvetica-Bold',
    color: colors.primary,
    marginBottom: 6,
    textTransform: 'uppercase',
    letterSpacing: 0.8,
  },
  cardMain: {
    fontSize: 10,
    fontFamily: 'Helvetica-Bold',
    color: colors.textDark,
    marginBottom: 3,
  },
  cardSub: {
    fontSize: 7.5,
    color: colors.textLight,
    marginBottom: 1.5,
  },

  // ── Section Headers ──
  sectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
    marginTop: 18,
  },
  sectionDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    backgroundColor: colors.primary,
    marginRight: 8,
  },
  sectionTitle: {
    fontSize: 11,
    fontFamily: 'Helvetica-Bold',
    color: colors.textDark,
    marginRight: 10,
  },
  sectionLine: {
    flex: 1,
    height: 1,
    backgroundColor: colors.border,
  },

  // ── Table ──
  table: {
    marginBottom: 0,
  },
  tableHeader: {
    flexDirection: 'row',
    backgroundColor: colors.text,
    paddingVertical: 9,
    paddingHorizontal: 12,
    borderRadius: 4,
  },
  tableHeaderCell: {
    fontSize: 7.5,
    fontFamily: 'Helvetica-Bold',
    color: colors.white,
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  tableRow: {
    flexDirection: 'row',
    paddingVertical: 10,
    paddingHorizontal: 12,
    borderBottomWidth: 1,
    borderBottomColor: colors.borderLight,
  },
  tableRowAlt: {
    backgroundColor: colors.background,
  },
  tableCell: {
    fontSize: 8.5,
    color: colors.text,
  },
  websiteName: {
    fontFamily: 'Helvetica-Bold',
    color: colors.textDark,
    fontSize: 8.5,
  },
  websiteDomain: {
    fontSize: 7,
    color: colors.textLight,
    marginTop: 1.5,
  },
  amountText: {
    fontFamily: 'Helvetica-Bold',
    color: colors.text,
  },

  col1: { width: '38%' },
  col2: { width: '10%', textAlign: 'center' },
  col3: { width: '17%', textAlign: 'right' },
  col4: { width: '17%', textAlign: 'right' },
  col5: { width: '18%', textAlign: 'right' },

  // ── Package Card ──
  packageCard: {
    marginBottom: 12,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: colors.border,
    overflow: 'hidden',
  },
  packageHeader: {
    backgroundColor: colors.text,
    paddingVertical: 10,
    paddingHorizontal: 14,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  packageName: {
    fontSize: 10,
    fontFamily: 'Helvetica-Bold',
    color: colors.white,
  },
  packageTypeBadge: {
    fontSize: 7,
    backgroundColor: colors.primary,
    color: colors.white,
    paddingVertical: 3,
    paddingHorizontal: 8,
    borderRadius: 10,
    fontFamily: 'Helvetica-Bold',
  },
  packageBody: {
    padding: 14,
  },
  packageInfoGrid: {
    flexDirection: 'row',
    marginBottom: 14,
    paddingBottom: 12,
    borderBottomWidth: 1,
    borderBottomColor: colors.borderLight,
  },
  packageInfoItem: {
    flex: 1,
    alignItems: 'center',
  },
  packageInfoLabel: {
    fontSize: 7,
    color: colors.textLight,
    marginBottom: 3,
    textTransform: 'uppercase',
    letterSpacing: 0.5,
  },
  packageInfoValue: {
    fontSize: 13,
    fontFamily: 'Helvetica-Bold',
    color: colors.primary,
  },

  // ── Websites Sub-table ──
  websitesTableHeader: {
    flexDirection: 'row',
    backgroundColor: colors.primaryLight,
    paddingVertical: 7,
    paddingHorizontal: 10,
    borderRadius: 4,
    marginBottom: 0,
  },
  websitesHeaderCell: {
    fontSize: 7,
    fontFamily: 'Helvetica-Bold',
    color: colors.primaryDark,
    textTransform: 'uppercase',
    letterSpacing: 0.4,
  },
  websitesRow: {
    flexDirection: 'row',
    paddingVertical: 8,
    paddingHorizontal: 10,
    borderBottomWidth: 1,
    borderBottomColor: colors.borderLight,
  },
  websitesCell: {
    fontSize: 8,
    color: colors.text,
  },
  wCol1: { width: '38%' },
  wCol2: { width: '12%', textAlign: 'center' },
  wCol3: { width: '12%', textAlign: 'center' },
  wCol4: { width: '18%', textAlign: 'center' },
  wCol5: { width: '20%', textAlign: 'right' },

  // ── Totals ──
  totalsSection: {
    marginTop: 18,
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  totalsBox: {
    width: 280,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: 6,
    overflow: 'hidden',
  },
  totalRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 8,
    paddingHorizontal: 14,
    borderBottomWidth: 1,
    borderBottomColor: colors.borderLight,
  },
  totalLabel: {
    fontSize: 8.5,
    color: colors.textLight,
  },
  totalValue: {
    fontSize: 8.5,
    fontFamily: 'Helvetica-Bold',
    color: colors.text,
  },
  grandTotalRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 11,
    paddingHorizontal: 14,
    backgroundColor: colors.primary,
    alignItems: 'center',
  },
  grandTotalLabel: {
    fontSize: 9,
    fontFamily: 'Helvetica-Bold',
    color: colors.white,
  },
  grandTotalValue: {
    fontSize: 16,
    fontFamily: 'Helvetica-Bold',
    color: colors.white,
  },

  // ── Payment Info ──
  paymentSection: {
    marginTop: 18,
    padding: 14,
    backgroundColor: colors.background,
    borderRadius: 6,
    borderWidth: 1,
    borderColor: colors.border,
  },
  paymentTitle: {
    fontSize: 9,
    fontFamily: 'Helvetica-Bold',
    color: colors.textDark,
    marginBottom: 10,
    textTransform: 'uppercase',
    letterSpacing: 0.6,
  },
  paymentGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 10,
  },
  paymentItem: {
    flex: 1,
    minWidth: 120,
  },
  paymentLabel: {
    fontSize: 7,
    color: colors.textLight,
    marginBottom: 2,
    textTransform: 'uppercase',
    letterSpacing: 0.4,
  },
  paymentValue: {
    fontSize: 8.5,
    fontFamily: 'Helvetica-Bold',
    color: colors.text,
  },
  paidBadge: {
    backgroundColor: colors.success,
    paddingVertical: 2,
    paddingHorizontal: 8,
    borderRadius: 10,
    alignSelf: 'flex-start',
  },
  paidBadgeText: {
    fontSize: 7,
    fontFamily: 'Helvetica-Bold',
    color: colors.white,
  },

  // ── Footer ──
  footer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
  },
  footerBar: {
    backgroundColor: colors.text,
    paddingVertical: 14,
    paddingHorizontal: 36,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  footerLeft: {
    flexDirection: 'column',
  },
  footerBrand: {
    fontSize: 9,
    fontFamily: 'Helvetica-Bold',
    color: colors.white,
    marginBottom: 2,
  },
  footerMeta: {
    fontSize: 7,
    color: '#94A3B8',
  },
  footerRight: {
    alignItems: 'flex-end',
  },
  footerThankYou: {
    fontSize: 8,
    color: colors.primary,
    fontFamily: 'Helvetica-Bold',
    marginBottom: 2,
  },
  footerCopy: {
    fontSize: 7,
    color: '#94A3B8',
  },
});

// ── Types ──
interface OrderItem {
  website_name?: string;
  website_domain?: string;
  website_da?: number;
  unit_price: number;
  content_service: boolean;
  content_service_price?: number;
  subtotal: number;
}

interface PackageAssignedWebsite {
  website_name: string;
  website_domain: string;
  website_da?: number;
  website_dr?: number;
  website_link_type?: string;
  website_base_price: number;
  assigned_da?: number;
}

interface PackageItem {
  package_name: string;
  package_type: string;
  quantity: number;
  unit_price: number;
  subtotal: number;
  assigned_websites?: PackageAssignedWebsite[];
}

interface OrderData {
  id: string;
  order_number: string;
  created_at: string;
  total_amount: number;
  status: string;
  payment_status: string;
  payment_method: string;
  transaction_id: string;
  order_type: string;
  items: OrderItem[];
  package_items?: PackageItem[];
}

interface UserData {
  first_name?: string;
  last_name?: string;
  display_name?: string;
  email: string;
  company?: string;
  country?: string;
  city?: string;
  phone?: string;
}

interface InvoicePDFProps {
  order: OrderData;
  user: UserData;
}

export default function InvoicePDF({ order, user }: InvoicePDFProps) {
  const formatDate = (dateString: string) =>
    new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric', month: 'long', day: 'numeric',
    });

  const formatCurrency = (amount: number) =>
    `$${amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

  const customerName =
    user.display_name ||
    [user.first_name, user.last_name].filter(Boolean).join(' ') ||
    'Guest';

  const individualSubtotal = order.items?.reduce((s, i) => s + (i.subtotal || 0), 0) || 0;
  const packageSubtotal = order.package_items?.reduce((s, p) => s + (p.subtotal || 0), 0) || 0;
  const showBothSubtotals = individualSubtotal > 0 && packageSubtotal > 0;

  const rowStyle = (idx: number) =>
    idx % 2 === 1 ? [styles.tableRow, styles.tableRowAlt] : [styles.tableRow];

  return (
    <Document>
      <Page size="A4" style={styles.page}>
        {/* Top accent bar */}
        <View style={styles.topBar} />

        <View style={styles.content}>
          {/* ── Header ── */}
          <View style={styles.header}>
            {/* Company info */}
            <View style={styles.companyBlock}>
              <Text style={styles.logo}>{COMPANY.name}</Text>
              <Text style={styles.tagline}>{COMPANY.tagline}</Text>
              <Text style={styles.companyMeta}>{COMPANY.address}</Text>
              <Text style={styles.companyMeta}>{COMPANY.city}</Text>
              <Text style={styles.companyMeta}>{COMPANY.country}</Text>
              <Text style={styles.companyMeta}>{COMPANY.email}</Text>
              <Text style={styles.companyMeta}>{COMPANY.phone}</Text>
              <Text style={styles.companyMeta}>{COMPANY.website}</Text>
              <Text style={styles.companyMeta}>{COMPANY.taxId}</Text>
            </View>

            {/* Invoice badge */}
            <View style={styles.invoiceBadge}>
              <Text style={styles.invoiceLabel}>INVOICE</Text>
              <View style={styles.invoiceNumberRow}>
                <Text style={styles.invoiceNumberLabel}>No.</Text>
                <Text style={styles.invoiceNumberValue}>#{order.order_number}</Text>
              </View>
            </View>
          </View>

          <View style={styles.divider} />

          {/* ── Info Cards ── */}
          <View style={styles.infoCardsGrid}>
            {/* Bill To */}
            <View style={styles.infoCard}>
              <Text style={styles.cardTitle}>Bill To</Text>
              <Text style={styles.cardMain}>{customerName}</Text>
              <Text style={styles.cardSub}>{user.email}</Text>
              {user.company ? <Text style={styles.cardSub}>{user.company}</Text> : null}
              {user.phone ? <Text style={styles.cardSub}>{user.phone}</Text> : null}
              {user.city ? <Text style={styles.cardSub}>{user.city}</Text> : null}
              {user.country ? <Text style={styles.cardSub}>{user.country}</Text> : null}
            </View>

            {/* Invoice Details */}
            <View style={styles.infoCard}>
              <Text style={styles.cardTitle}>Invoice Details</Text>
              <Text style={styles.cardMain}>{formatDate(order.created_at)}</Text>
              <Text style={styles.cardSub}>Invoice #{order.order_number}</Text>
              <Text style={styles.cardSub}>Payment: {order.payment_method || 'N/A'}</Text>
              {order.transaction_id ? (
                <Text style={styles.cardSub}>Txn: {order.transaction_id}</Text>
              ) : null}
            </View>

            {/* Summary */}
            <View style={styles.infoCard}>
              <Text style={styles.cardTitle}>Summary</Text>
              <Text style={styles.cardMain}>{formatCurrency(order.total_amount)}</Text>
              {(order.items?.length || 0) > 0 ? (
                <Text style={styles.cardSub}>{order.items.length} Individual item(s)</Text>
              ) : null}
              {(order.package_items?.length || 0) > 0 ? (
                <Text style={styles.cardSub}>{order.package_items!.length} Package(s)</Text>
              ) : null}
            </View>
          </View>

          {/* ── Individual Items ── */}
          {order.items && order.items.length > 0 && (
            <>
              <View style={styles.sectionHeader}>
                <View style={styles.sectionDot} />
                <Text style={styles.sectionTitle}>Individual Items</Text>
                <View style={styles.sectionLine} />
              </View>
              <View style={styles.table}>
                <View style={styles.tableHeader}>
                  <Text style={[styles.tableHeaderCell, styles.col1]}>Website</Text>
                  <Text style={[styles.tableHeaderCell, styles.col2]}>DA</Text>
                  <Text style={[styles.tableHeaderCell, styles.col3]}>Unit Price</Text>
                  <Text style={[styles.tableHeaderCell, styles.col4]}>Content</Text>
                  <Text style={[styles.tableHeaderCell, styles.col5]}>Subtotal</Text>
                </View>
                {order.items.map((item, idx) => (
                  <View key={idx} style={rowStyle(idx)}>
                    <View style={[styles.tableCell, styles.col1]}>
                      <Text style={styles.websiteName}>{item.website_name || 'N/A'}</Text>
                      {item.website_domain ? (
                        <Text style={styles.websiteDomain}>{item.website_domain}</Text>
                      ) : null}
                    </View>
                    <Text style={[styles.tableCell, styles.col2]}>{item.website_da ?? 'N/A'}</Text>
                    <Text style={[styles.tableCell, styles.col3]}>{formatCurrency(item.unit_price)}</Text>
                    <Text style={[styles.tableCell, styles.col4]}>
                      {item.content_service ? formatCurrency(item.content_service_price || 0) : '—'}
                    </Text>
                    <Text style={[styles.tableCell, styles.col5, styles.amountText]}>
                      {formatCurrency(item.subtotal)}
                    </Text>
                  </View>
                ))}
              </View>
            </>
          )}

          {/* ── Package Items ── */}
          {order.package_items && order.package_items.length > 0 && (
            <>
              <View style={styles.sectionHeader}>
                <View style={styles.sectionDot} />
                <Text style={styles.sectionTitle}>Package Items</Text>
                <View style={styles.sectionLine} />
              </View>
              {order.package_items.map((pkg, idx) => (
                <View key={idx} style={styles.packageCard}>
                  <View style={styles.packageHeader}>
                    <Text style={styles.packageName}>{pkg.package_name}</Text>
                    <Text style={styles.packageTypeBadge}>{pkg.package_type}</Text>
                  </View>
                  <View style={styles.packageBody}>
                    <View style={styles.packageInfoGrid}>
                      <View style={styles.packageInfoItem}>
                        <Text style={styles.packageInfoLabel}>Quantity</Text>
                        <Text style={styles.packageInfoValue}>{pkg.quantity}</Text>
                      </View>
                      <View style={styles.packageInfoItem}>
                        <Text style={styles.packageInfoLabel}>Unit Price</Text>
                        <Text style={styles.packageInfoValue}>{formatCurrency(pkg.unit_price)}</Text>
                      </View>
                      <View style={styles.packageInfoItem}>
                        <Text style={styles.packageInfoLabel}>Subtotal</Text>
                        <Text style={styles.packageInfoValue}>{formatCurrency(pkg.subtotal)}</Text>
                      </View>
                    </View>

                    {pkg.assigned_websites && pkg.assigned_websites.length > 0 && (
                      <>
                        <Text style={{ fontSize: 7.5, fontFamily: 'Helvetica-Bold', color: colors.textLight, marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                          Included Websites ({pkg.assigned_websites.length})
                        </Text>
                        <View style={styles.websitesTableHeader}>
                          <Text style={[styles.websitesHeaderCell, styles.wCol1]}>Website</Text>
                          <Text style={[styles.websitesHeaderCell, styles.wCol2]}>DA</Text>
                          <Text style={[styles.websitesHeaderCell, styles.wCol3]}>DR</Text>
                          <Text style={[styles.websitesHeaderCell, styles.wCol4]}>Link Type</Text>
                          <Text style={[styles.websitesHeaderCell, styles.wCol5]}>Price</Text>
                        </View>
                        {pkg.assigned_websites.map((w, wIdx) => (
                          <View key={wIdx} style={styles.websitesRow}>
                            <View style={[styles.websitesCell, styles.wCol1]}>
                              <Text style={styles.websiteName}>{w.website_name}</Text>
                              {w.website_domain ? (
                                <Text style={styles.websiteDomain}>{w.website_domain}</Text>
                              ) : null}
                            </View>
                            <Text style={[styles.websitesCell, styles.wCol2]}>
                              {w.assigned_da || w.website_da || 'N/A'}
                            </Text>
                            <Text style={[styles.websitesCell, styles.wCol3]}>
                              {w.website_dr || 'N/A'}
                            </Text>
                            <Text style={[styles.websitesCell, styles.wCol4]}>
                              {w.website_link_type || 'Dofollow'}
                            </Text>
                            <Text style={[styles.websitesCell, styles.wCol5, styles.amountText]}>
                              {formatCurrency(w.website_base_price)}
                            </Text>
                          </View>
                        ))}
                      </>
                    )}
                  </View>
                </View>
              ))}
            </>
          )}

          {/* ── Totals ── */}
          <View style={styles.totalsSection}>
            <View style={styles.totalsBox}>
              {showBothSubtotals && (
                <>
                  <View style={styles.totalRow}>
                    <Text style={styles.totalLabel}>Individual Items</Text>
                    <Text style={styles.totalValue}>{formatCurrency(individualSubtotal)}</Text>
                  </View>
                  <View style={styles.totalRow}>
                    <Text style={styles.totalLabel}>Package Items</Text>
                    <Text style={styles.totalValue}>{formatCurrency(packageSubtotal)}</Text>
                  </View>
                </>
              )}
              <View style={styles.grandTotalRow}>
                <Text style={styles.grandTotalLabel}>Total Amount</Text>
                <Text style={styles.grandTotalValue}>{formatCurrency(order.total_amount)}</Text>
              </View>
            </View>
          </View>

          {/* ── Payment Info ── */}
          <View style={styles.paymentSection}>
            <Text style={styles.paymentTitle}>Payment Information</Text>
            <View style={styles.paymentGrid}>
              <View style={styles.paymentItem}>
                <Text style={styles.paymentLabel}>Method</Text>
                <Text style={styles.paymentValue}>{order.payment_method || 'N/A'}</Text>
              </View>
              {order.transaction_id ? (
                <View style={styles.paymentItem}>
                  <Text style={styles.paymentLabel}>Transaction ID</Text>
                  <Text style={styles.paymentValue}>{order.transaction_id}</Text>
                </View>
              ) : null}
              <View style={styles.paymentItem}>
                <Text style={styles.paymentLabel}>Date</Text>
                <Text style={styles.paymentValue}>{formatDate(order.created_at)}</Text>
              </View>
              <View style={styles.paymentItem}>
                <Text style={styles.paymentLabel}>Status</Text>
                <View style={styles.paidBadge}>
                  <Text style={styles.paidBadgeText}>PAID</Text>
                </View>
              </View>
            </View>
          </View>
        </View>

        {/* ── Footer ── */}
        <View style={styles.footer}>
          <View style={styles.footerBar}>
            <View style={styles.footerLeft}>
              <Text style={styles.footerBrand}>{COMPANY.name}</Text>
              <Text style={styles.footerMeta}>{COMPANY.email}  ·  {COMPANY.phone}</Text>
              <Text style={styles.footerMeta}>{COMPANY.website}</Text>
            </View>
            <View style={styles.footerRight}>
              <Text style={styles.footerThankYou}>Thank you for your business!</Text>
              <Text style={styles.footerCopy}>© 2026 {COMPANY.name}. All rights reserved.</Text>
            </View>
          </View>
        </View>
      </Page>
    </Document>
  );
}