/**
 * Template "Moderne" — bandeau coloré en header, mise en page contemporaine.
 *
 * Cible : agences, studios, freelances créatifs. L'accent color est dominant :
 * bandeau header, ligne de séparation, total TTC. Le logo se pose sur le
 * bandeau.
 */

import React from 'react'
import { Document, Page, View, Text, Image, StyleSheet } from '@react-pdf/renderer'
import {
  type InvoiceTemplateProps,
  PALETTE,
  formatCents,
  formatDate,
  formatQuantity,
  formatTvaRate,
  formatAddress,
} from '#pdf-templates/common'

const styles = StyleSheet.create({
  page: {
    fontSize: 10,
    color: PALETTE.ink,
    fontFamily: 'Helvetica',
    lineHeight: 1.5,
  },
  // Bandeau coloré pleine largeur en haut
  banner: {
    paddingTop: 36,
    paddingBottom: 28,
    paddingHorizontal: 56,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
  },
  bannerLeft: { flex: 2 },
  bannerRight: { flex: 1, alignItems: 'flex-end' },
  invoiceTitle: { fontSize: 26, fontWeight: 'bold', color: PALETTE.paper, letterSpacing: 1 },
  invoiceNumero: { fontSize: 11, color: PALETTE.paper, opacity: 0.85, marginTop: 4 },
  bannerCompany: { fontSize: 13, color: PALETTE.paper, fontWeight: 'bold' },
  bannerMeta: { fontSize: 8, color: PALETTE.paper, opacity: 0.85 },
  logo: { width: 60, height: 24, objectFit: 'contain', marginBottom: 6 },
  // Corps
  body: { paddingTop: 32, paddingHorizontal: 56, paddingBottom: 36, flexGrow: 1 },
  metaRow: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 24 },
  metaBlock: { flex: 1 },
  metaLabel: {
    fontSize: 8,
    textTransform: 'uppercase',
    color: PALETTE.ink3,
    marginBottom: 4,
  },
  clientName: { fontSize: 12, fontWeight: 'bold' },
  // Table
  table: { marginBottom: 16 },
  tableHeader: {
    flexDirection: 'row',
    paddingVertical: 8,
    paddingHorizontal: 6,
  },
  tableHeaderText: { fontSize: 8, textTransform: 'uppercase', fontWeight: 'bold', color: PALETTE.paper },
  tableRow: {
    flexDirection: 'row',
    paddingVertical: 8,
    paddingHorizontal: 6,
    borderBottomWidth: 0.5,
    borderBottomColor: PALETTE.line,
  },
  cellDesc: { flex: 4 },
  cellQty: { flex: 1, textAlign: 'right' },
  cellPu: { flex: 1.5, textAlign: 'right' },
  cellTva: { flex: 1, textAlign: 'right' },
  cellTotal: { flex: 1.5, textAlign: 'right' },
  // Totaux
  totalsBlock: { alignSelf: 'flex-end', width: '45%', marginBottom: 24 },
  totalRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 3 },
  totalRowGrand: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 10,
    paddingHorizontal: 12,
    marginTop: 6,
  },
  totalLabel: { color: PALETTE.ink2 },
  grandLabel: { fontSize: 12, fontWeight: 'bold', color: PALETTE.paper },
  grandAmount: { fontSize: 14, fontWeight: 'bold', color: PALETTE.paper },
  // TVA breakdown
  tvaBlock: { marginBottom: 16, width: '60%' },
  tvaHeader: {
    flexDirection: 'row',
    borderBottomWidth: 0.5,
    borderBottomColor: PALETTE.line,
    paddingBottom: 3,
  },
  tvaRow: { flexDirection: 'row', paddingVertical: 2 },
  tvaCell: { flex: 1, textAlign: 'right', fontSize: 9 },
  tvaCellLeft: { flex: 1, textAlign: 'left', fontSize: 9, color: PALETTE.ink2 },
  cellHead: { fontSize: 8, textTransform: 'uppercase', color: PALETTE.ink3, fontWeight: 'bold' },
  // Footer
  paymentBlock: { marginTop: 12, marginBottom: 12 },
  paymentLabel: {
    fontSize: 8,
    textTransform: 'uppercase',
    color: PALETTE.ink3,
    marginBottom: 4,
  },
  legalBlock: {
    marginTop: 'auto',
    paddingTop: 12,
    borderTopWidth: 0.5,
    borderTopColor: PALETTE.line,
    fontSize: 7,
    color: PALETTE.ink3,
    lineHeight: 1.4,
  },
})

export function ModerneTemplate(props: InvoiceTemplateProps) {
  const accentBg = { backgroundColor: props.accentColor }
  const issuerAddress = formatAddress({
    line1: props.issuer.addressLine1,
    line2: props.issuer.addressLine2,
    zip: props.issuer.addressZip,
    city: props.issuer.addressCity,
    country: props.issuer.addressCountry,
  })
  const clientAddress = formatAddress({
    line1: props.client.addressLine1,
    line2: props.client.addressLine2,
    zip: props.client.addressZip,
    city: props.client.addressCity,
    country: props.client.addressCountry,
  })
  const showTvaBreakdown = props.tvaBreakdown.length > 1

  return (
    <Document>
      <Page size="A4" style={styles.page}>
        {/* Bandeau coloré */}
        <View style={[styles.banner, accentBg]}>
          <View style={styles.bannerLeft}>
            <Text style={styles.invoiceTitle}>FACTURE</Text>
            <Text style={styles.invoiceNumero}>N° {props.numero}</Text>
          </View>
          <View style={styles.bannerRight}>
            {props.logoUrl ? <Image src={props.logoUrl} style={styles.logo} /> : null}
            <Text style={styles.bannerCompany}>{props.issuer.companyName ?? '—'}</Text>
            {issuerAddress.slice(0, 2).map((line, i) => (
              <Text key={`bma-${i}`} style={styles.bannerMeta}>
                {line}
              </Text>
            ))}
            {props.issuer.siret ? (
              <Text style={styles.bannerMeta}>SIRET {props.issuer.siret}</Text>
            ) : null}
          </View>
        </View>

        <View style={styles.body}>
          {/* Méta : client + dates */}
          <View style={styles.metaRow}>
            <View style={styles.metaBlock}>
              <Text style={styles.metaLabel}>Adressée à</Text>
              <Text style={styles.clientName}>{props.client.name}</Text>
              {clientAddress.map((line, i) => (
                <Text key={`cli-${i}`}>{line}</Text>
              ))}
              {props.client.siret ? <Text>SIRET {props.client.siret}</Text> : null}
              {props.client.tvaIntra ? <Text>TVA {props.client.tvaIntra}</Text> : null}
            </View>
            <View style={[styles.metaBlock, { alignItems: 'flex-end' }]}>
              <Text style={styles.metaLabel}>Émise le</Text>
              <Text style={{ marginBottom: 6 }}>{formatDate(props.issueDate)}</Text>
              <Text style={styles.metaLabel}>Échéance</Text>
              <Text>{formatDate(props.dueDate)}</Text>
              <Text style={{ fontSize: 9, color: PALETTE.ink3, marginTop: 2 }}>
                {props.paymentTermsDays} jour{props.paymentTermsDays > 1 ? 's' : ''} de
                délai
              </Text>
            </View>
          </View>

          {/* Table */}
          <View style={styles.table}>
            <View style={[styles.tableHeader, accentBg]}>
              <Text style={[styles.cellDesc, styles.tableHeaderText]}>Désignation</Text>
              <Text style={[styles.cellQty, styles.tableHeaderText]}>Qté</Text>
              <Text style={[styles.cellPu, styles.tableHeaderText]}>P.U. HT</Text>
              <Text style={[styles.cellTva, styles.tableHeaderText]}>TVA</Text>
              <Text style={[styles.cellTotal, styles.tableHeaderText]}>Total HT</Text>
            </View>
            {props.lines.map((l) => (
              <View key={l.id} style={styles.tableRow}>
                <Text style={styles.cellDesc}>{l.description}</Text>
                <Text style={styles.cellQty}>{formatQuantity(l.quantity)}</Text>
                <Text style={styles.cellPu}>{formatCents(l.unitPriceCents)}</Text>
                <Text style={styles.cellTva}>{formatTvaRate(l.tvaRate)}</Text>
                <Text style={styles.cellTotal}>{formatCents(l.totalHtCents)}</Text>
              </View>
            ))}
          </View>

          {showTvaBreakdown ? (
            <View style={styles.tvaBlock}>
              <View style={styles.tvaHeader}>
                <Text style={[styles.tvaCellLeft, styles.cellHead]}>Taux</Text>
                <Text style={[styles.tvaCell, styles.cellHead]}>Base HT</Text>
                <Text style={[styles.tvaCell, styles.cellHead]}>Montant TVA</Text>
              </View>
              {props.tvaBreakdown.map((b) => (
                <View key={`tva-${b.rate}`} style={styles.tvaRow}>
                  <Text style={styles.tvaCellLeft}>{formatTvaRate(b.rate)}</Text>
                  <Text style={styles.tvaCell}>{formatCents(b.htCents)}</Text>
                  <Text style={styles.tvaCell}>{formatCents(b.tvaCents)}</Text>
                </View>
              ))}
            </View>
          ) : null}

          {/* Totaux */}
          <View style={styles.totalsBlock}>
            <View style={styles.totalRow}>
              <Text style={styles.totalLabel}>Total HT</Text>
              <Text>{formatCents(props.amountHtCents)}</Text>
            </View>
            <View style={styles.totalRow}>
              <Text style={styles.totalLabel}>TVA</Text>
              <Text>{formatCents(props.amountTvaCents)}</Text>
            </View>
            <View style={[styles.totalRowGrand, accentBg]}>
              <Text style={styles.grandLabel}>Total TTC</Text>
              <Text style={styles.grandAmount}>{formatCents(props.amountTtcCents)}</Text>
            </View>
          </View>

          {props.rib.iban || props.rib.bic ? (
            <View style={styles.paymentBlock}>
              <Text style={styles.paymentLabel}>Coordonnées de paiement</Text>
              {props.rib.bankName ? <Text>{props.rib.bankName}</Text> : null}
              {props.rib.iban ? <Text>IBAN : {props.rib.iban}</Text> : null}
              {props.rib.bic ? <Text>BIC : {props.rib.bic}</Text> : null}
            </View>
          ) : null}

          {props.footerNotes ? (
            <View style={styles.paymentBlock}>
              <Text style={styles.paymentLabel}>Notes</Text>
              <Text>{props.footerNotes}</Text>
            </View>
          ) : null}

          <View style={styles.legalBlock}>
            <Text>{props.penaltyRateText}</Text>
            <Text>{props.escompteText}</Text>
            {props.footerLegalText ? <Text>{props.footerLegalText}</Text> : null}
            {props.issuer.rcs || props.issuer.capital ? (
              <Text>
                {[props.issuer.formeJuridique, props.issuer.capital, props.issuer.rcs]
                  .filter(Boolean)
                  .join(' · ')}
              </Text>
            ) : null}
          </View>
        </View>
      </Page>
    </Document>
  )
}
