import React from "react";
import {
  Document, Page, Text, View, StyleSheet, Font,
} from "@react-pdf/renderer";
import { styles, colors } from "./styles";

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

export type InvoicePdfData = {
  type: "FACTURE" | "DEVIS";
  number: string;
  status: string;
  issueDate: string;
  dueDate?: string | null;
  validUntil?: string | null;
  reference?: string | null;
  notes?: string | null;
  terms?: string | null;
  currency: string;
  seller: {
    name: string;
    email?: string | null;
    phone?: string | null;
    address?: string | null;
    city?: string | null;
    postalCode?: string | null;
    country?: string | null;
    vatNumber?: string | null;
    siret?: string | null;
  };
  customer: {
    name: string;
    email?: string | null;
    phone?: string | null;
    address?: string | null;
    city?: string | null;
    postalCode?: string | null;
    country?: string | null;
    vatNumber?: string | null;
  } | null;
  items: {
    description: string;
    quantity: number;
    unitPrice: number;
    taxRate: number;
    total: number;
    unit?: string | null;
  }[];
  subtotal: number;
  taxAmount: number;
  discountAmount: number;
  total: number;
  amountPaid?: number;
  amountDue?: number;
};

// ─── Helpers ───────────────────────────────────────────────────

function fmt(n: number, currency = "XOF") {
  if (currency === "XOF" || currency === "XAF") {
    return new Intl.NumberFormat("fr-FR", { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(n) + " F CFA";
  }
  return new Intl.NumberFormat("fr-FR", { style: "currency", currency }).format(n);
}

function addr(obj: { address?: string | null; city?: string | null; postalCode?: string | null; country?: string | null }) {
  return [obj.address, [obj.postalCode, obj.city].filter(Boolean).join(" "), obj.country]
    .filter(Boolean)
    .join("\n");
}

// ─── Components ────────────────────────────────────────────────

function InfoBlock({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <View style={styles.infoBlock}>
      <Text style={styles.infoTitle}>{title}</Text>
      {children}
    </View>
  );
}

function PartyCard({ title, name, email, phone, address, vatNumber }: {
  title: string; name: string; email?: string | null; phone?: string | null;
  address?: string; vatNumber?: string | null;
}) {
  return (
    <View style={[styles.infoBlock, styles.partyCard]}>
      <Text style={styles.infoTitle}>{title}</Text>
      <Text style={styles.infoValueBold}>{name}</Text>
      {email      && <Text style={styles.infoValue}>{email}</Text>}
      {phone      && <Text style={styles.infoValue}>{phone}</Text>}
      {address    && <Text style={[styles.infoValue, { marginTop: 3 }]}>{address}</Text>}
      {vatNumber  && <Text style={[styles.infoValue, { marginTop: 3, color: colors.muted }]}>TVA : {vatNumber}</Text>}
    </View>
  );
}

// ─── Main document ─────────────────────────────────────────────

export function InvoicePdf({ data }: { data: InvoicePdfData }) {
  const hasDiscount = data.discountAmount > 0;
  const hasTax      = data.taxAmount > 0;
  const dateLabel   = data.type === "DEVIS" ? "Valide jusqu'au" : "Échéance";
  const dateValue   = data.type === "DEVIS" ? data.validUntil : data.dueDate;

  return (
    <Document>
      <Page size="A4" style={styles.page}>

        {/* ── Header ── */}
        <View style={styles.header}>
          <View style={styles.orgBlock}>
            <Text style={styles.orgName}>{data.seller.name}</Text>
            <Text style={styles.orgMeta}>
              {[data.seller.email, data.seller.phone].filter(Boolean).join("  ·  ")}
              {"\n"}
              {addr(data.seller)}
              {data.seller.vatNumber ? `\nN° TVA : ${data.seller.vatNumber}` : ""}
              {data.seller.siret     ? `\nSIRET : ${data.seller.siret}`      : ""}
            </Text>
          </View>
          <View style={styles.docTypeBlock}>
            <Text style={styles.docType}>{data.type}</Text>
            <Text style={styles.docNumber}>N° {data.number}</Text>
          </View>
        </View>

        {/* ── Dates + Parties ── */}
        <View style={styles.infoRow}>
          {/* Dates */}
          <View style={{ width: 130 }}>
            <InfoBlock title="Date d'émission">
              <Text style={styles.infoValue}>{data.issueDate}</Text>
            </InfoBlock>
            {dateValue && (
              <View style={{ marginTop: 8 }}>
                <InfoBlock title={dateLabel}>
                  <Text style={styles.infoValue}>{dateValue}</Text>
                </InfoBlock>
              </View>
            )}
            {data.reference && (
              <View style={{ marginTop: 8 }}>
                <InfoBlock title="Référence">
                  <Text style={styles.infoValue}>{data.reference}</Text>
                </InfoBlock>
              </View>
            )}
          </View>

          {/* Seller */}
          <PartyCard
            title="De"
            name={data.seller.name}
            email={data.seller.email}
            phone={data.seller.phone}
            address={addr(data.seller)}
            vatNumber={data.seller.vatNumber}
          />

          {/* Customer */}
          {data.customer ? (
            <PartyCard
              title="Pour"
              name={data.customer.name}
              email={data.customer.email}
              phone={data.customer.phone}
              address={addr(data.customer)}
              vatNumber={data.customer.vatNumber}
            />
          ) : (
            <View style={[styles.infoBlock, styles.partyCard]}>
              <Text style={styles.infoTitle}>Pour</Text>
              <Text style={[styles.infoValue, { color: colors.muted }]}>—</Text>
            </View>
          )}
        </View>

        {/* ── Items table ── */}
        <View style={styles.table}>
          {/* Header */}
          <View style={styles.tableHeader}>
            <Text style={[styles.tableHeaderCell, styles.colDesc]}>Description</Text>
            <Text style={[styles.tableHeaderCell, styles.colQty]}>Qté</Text>
            <Text style={[styles.tableHeaderCell, styles.colUnit]}>P.U.</Text>
            {hasTax && <Text style={[styles.tableHeaderCell, styles.colTax]}>TVA</Text>}
            <Text style={[styles.tableHeaderCell, styles.colTotal]}>Total HT</Text>
          </View>

          {/* Rows */}
          {data.items.map((item, i) => (
            <View key={i} style={[styles.tableRow, i % 2 === 1 ? styles.tableRowAlt : {}]}>
              <View style={styles.colDesc}>
                <Text style={styles.tableCell}>{item.description}</Text>
                {item.unit && <Text style={styles.tableCellMuted}>Unité : {item.unit}</Text>}
              </View>
              <Text style={[styles.tableCell, styles.colQty]}>{item.quantity}</Text>
              <Text style={[styles.tableCell, styles.colUnit]}>{fmt(item.unitPrice, data.currency)}</Text>
              {hasTax && <Text style={[styles.tableCell, styles.colTax]}>{item.taxRate}%</Text>}
              <Text style={[styles.tableCell, styles.colTotal]}>{fmt(item.total, data.currency)}</Text>
            </View>
          ))}
        </View>

        {/* ── Totals ── */}
        <View style={styles.totalsSection}>
          <View style={styles.totalsBox}>
            <View style={styles.totalRow}>
              <Text style={styles.totalLabel}>Sous-total HT</Text>
              <Text style={styles.totalValue}>{fmt(data.subtotal, data.currency)}</Text>
            </View>
            {hasDiscount && (
              <View style={styles.totalRow}>
                <Text style={styles.totalLabel}>Remise</Text>
                <Text style={[styles.totalValue, { color: colors.success }]}>- {fmt(data.discountAmount, data.currency)}</Text>
              </View>
            )}
            {hasTax && (
              <View style={styles.totalRow}>
                <Text style={styles.totalLabel}>TVA</Text>
                <Text style={styles.totalValue}>{fmt(data.taxAmount, data.currency)}</Text>
              </View>
            )}
            <View style={styles.totalGrandRow}>
              <Text style={styles.totalGrandLabel}>Total TTC</Text>
              <Text style={styles.totalGrandValue}>{fmt(data.total, data.currency)}</Text>
            </View>
            {data.amountPaid !== undefined && data.amountPaid > 0 && (
              <View style={[styles.totalRow, { marginTop: 4 }]}>
                <Text style={styles.totalLabel}>Déjà réglé</Text>
                <Text style={[styles.totalValue, { color: colors.success }]}>{fmt(data.amountPaid, data.currency)}</Text>
              </View>
            )}
            {data.amountDue !== undefined && data.amountDue > 0 && (
              <View style={styles.totalRow}>
                <Text style={[styles.totalLabel, { fontFamily: "Helvetica-Bold" }]}>Reste à payer</Text>
                <Text style={[styles.totalValue, { fontFamily: "Helvetica-Bold", color: colors.danger }]}>{fmt(data.amountDue, data.currency)}</Text>
              </View>
            )}
          </View>
        </View>

        {/* ── Notes ── */}
        {data.notes && (
          <View style={styles.notesSection}>
            <Text style={styles.notesTitle}>Notes</Text>
            <Text style={styles.notesText}>{data.notes}</Text>
          </View>
        )}
        {data.terms && (
          <View style={styles.notesSection}>
            <Text style={styles.notesTitle}>Conditions</Text>
            <Text style={styles.notesText}>{data.terms}</Text>
          </View>
        )}

        {/* ── Footer ── */}
        <View style={styles.footer} fixed>
          <Text style={styles.footerText}>{data.seller.name}</Text>
          <Text style={styles.footerText}>{data.type} N° {data.number}</Text>
          <Text style={styles.footerText} render={({ pageNumber, totalPages }) => `Page ${pageNumber} / ${totalPages}`} />
        </View>

      </Page>
    </Document>
  );
}
