import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';

export type InvoiceLang = 'sv' | 'en';
export interface InvoiceItem { description: string; quantity: number; unit_price: number; vat_rate: number }
export interface BilledTo { name: string; street?: string; postal_code?: string; city?: string; country?: string; vat?: string; customer_ref?: string }
export interface InvoiceData {
  invoice_number: string; lang: InvoiceLang; issue_date: string; due_date: string;
  currency: string; items: InvoiceItem[]; billed_to: BilledTo; notes?: string | null;
  kind?: 'invoice' | 'credit'; credited_number?: string | null;
  issuer_entity?: 'se' | 'us';
}

export const EU_COUNTRIES = ['Austria','Belgium','Bulgaria','Croatia','Cyprus','Czech Republic','Denmark','Estonia','Finland','France','Germany','Greece','Hungary','Ireland','Italy','Latvia','Lithuania','Luxembourg','Malta','Netherlands','Poland','Portugal','Romania','Slovakia','Slovenia','Spain'];
export const OTHER_COUNTRIES = ['Norway','United Kingdom','Switzerland','United States','United Arab Emirates','Israel','Ukraine','Canada','Other'];
export type VatMode = 'domestic' | 'eu_reverse' | 'export';
export const COUNTRY_SV: Record<string, string> = { Sweden: 'Sverige', Austria: 'Österrike', Belgium: 'Belgien', Bulgaria: 'Bulgarien', Croatia: 'Kroatien', Cyprus: 'Cypern', 'Czech Republic': 'Tjeckien', Denmark: 'Danmark', Estonia: 'Estland', Finland: 'Finland', France: 'Frankrike', Germany: 'Tyskland', Greece: 'Grekland', Hungary: 'Ungern', Ireland: 'Irland', Italy: 'Italien', Latvia: 'Lettland', Lithuania: 'Litauen', Luxembourg: 'Luxemburg', Malta: 'Malta', Netherlands: 'Nederländerna', Poland: 'Polen', Portugal: 'Portugal', Romania: 'Rumänien', Slovakia: 'Slovakien', Slovenia: 'Slovenien', Spain: 'Spanien', Norway: 'Norge', 'United Kingdom': 'Storbritannien', Switzerland: 'Schweiz', 'United States': 'USA', 'United Arab Emirates': 'Förenade Arabemiraten', Israel: 'Israel', Ukraine: 'Ukraina', Canada: 'Kanada', Other: 'Annat land' };
export const countryLabel = (c: string) => COUNTRY_SV[c] || c;
const SV_ALIASES: Record<string, string> = { sverige: 'Sweden', nederländerna: 'Netherlands', holland: 'Netherlands', tyskland: 'Germany', danmark: 'Denmark', finland: 'Finland', frankrike: 'France', spanien: 'Spain', italien: 'Italy', belgien: 'Belgium', polen: 'Poland', österrike: 'Austria', irland: 'Ireland', norge: 'Norway', storbritannien: 'United Kingdom', usa: 'United States' };
export const normalizeCountry = (c?: string) => { const x = (c || '').trim(); return SV_ALIASES[x.toLowerCase()] || x; };
export const vatModeFor = (country?: string): VatMode => {
  const c = normalizeCountry(country);
  if (!c || c === 'Sweden') return 'domestic';
  return EU_COUNTRIES.includes(c) ? 'eu_reverse' : 'export';
};
export const applyVatMode = (items: InvoiceItem[], country?: string) =>
  vatModeFor(country) === 'domestic' ? items : items.map((i) => ({ ...i, vat_rate: 0 }));

export const ISSUER = {
  name: 'Suteki Studios', street: 'Duvkullavägen 38 D', postal: '172 37', city: 'Sundbyberg', country: 'Sweden',
  companyRegistrationNumber: '559382-1191',
  usStreet: '16192 Coastal Highway', usPostal: '19958', usCity: 'Lewes', usRegion: 'Delaware', usCountry: 'USA',
  usEin: 'EIN 61-2331967',
  email: 'info@sutekistudios.com', website: 'sutekistudios.com',
  iban: 'GB62 TRWI 2308 0126 7457 34', bic: 'TRWIGB2LXXX',
  bank: 'Wise Payments Limited, 1st Floor, Worship Square, 65 Clifton Street, London, EC2A 4JE, United Kingdom',
};

/** Wise receiving accounts per invoice currency (account holder "SUTEKI"). */
export function bankRows(currency: string, lang: 'sv' | 'en'): string[][] {
  const sv = lang === 'sv';
  const name = sv ? 'Kontoinnehavare' : 'Account holder';
  const bank = sv ? 'Bank och adress' : 'Bank name and address';
  switch ((currency || 'SEK').toUpperCase()) {
    case 'USD':
      return [
        [name, 'SUTEKI'],
        [sv ? 'Kontotyp' : 'Account type', 'Checking'],
        [sv ? 'Routingnummer (wire/ACH, inom USA)' : 'Routing number (wire/ACH, from US)', '101019628'],
        [sv ? 'Kontonummer (inom USA)' : 'Account number (from US)', '213182904320'],
        [sv ? 'Swift/BIC (utanför USA)' : 'Swift/BIC (from outside US)', 'TRWIUS35XXX'],
        [bank, 'Wise US Inc, 108 W 13th St, Wilmington, DE, 19801, United States'],
      ];
    case 'EUR':
      return [
        [name, 'SUTEKI'],
        ['IBAN', 'BE83 9054 6641 5615'],
        [sv ? 'Swift/BIC (utanför SEPA)' : 'Swift/BIC (from outside SEPA)', 'TRWIBEB1XXX'],
        [bank, 'Wise, Rue du Trône 100, 3rd floor, Brussels, 1050, Belgium'],
      ];
    default:
      return [
        [name, 'SUTEKI'],
        ['IBAN', 'GB62 TRWI 2308 0126 7457 34'],
        ['Swift/BIC', 'TRWIGB2LXXX'],
        [bank, 'Wise Payments Limited, 1st Floor, Worship Square, 65 Clifton Street, London, EC2A 4JE, United Kingdom'],
      ];
  }
}

const T = {
  sv: { title: 'Faktura', number: 'Fakturanummer', issue: 'Fakturadatum', due: 'Förfallodatum', billed: 'Fakturamottagare', customerRef: 'Er referens',
    issued: 'Avsändare', dueBy: 'att betala senast', product: 'Produkt eller tjänst', qty: 'Antal', unit: 'Á-pris', tax: 'Moms',
    total: 'Summa', exTax: 'Summa exkl. moms', taxTotal: 'Total moms', amountDue: 'Att betala', bankTitle: 'Betala via banköverföring',
    bankNote: 'Ange referensen vid betalning', ref: 'Referens', name: 'Namn', bankName: 'Bank och adress', notes: 'Övrigt',
    vat: 'moms',
    creditTitle: 'Kreditfaktura', creditRef: 'Krediterar faktura', creditAmount: 'Kreditbelopp', creditNote: 'Beloppet krediteras och ska inte betalas.',
    eu_reverse: 'Omvänd skattskyldighet (reverse charge) enligt artikel 196 i rådets direktiv 2006/112/EG. Köparen redovisar momsen.', export: 'Tjänsten är undantagen från svensk moms — omsättning utanför EU.' },
  en: { title: 'Invoice', number: 'Invoice number', issue: 'Issue date', due: 'Due date', billed: 'Billed to', customerRef: 'Your reference',
    issued: 'Issued by', dueBy: 'due by', product: 'Product or service', qty: 'Quantity', unit: 'Unit price', tax: 'VAT',
    total: 'Total', exTax: 'Total excluding VAT', taxTotal: 'Total VAT', amountDue: 'Amount due', bankTitle: 'Pay by bank transfer',
    bankNote: 'Make sure you enter the reference', ref: 'Reference', name: 'Name', bankName: 'Bank name and address', notes: 'Notes',
    vat: 'VAT',
    creditTitle: 'Credit note', creditRef: 'Credits invoice', creditAmount: 'Credit amount', creditNote: 'This amount is credited and should not be paid.',
    eu_reverse: 'Reverse charge — VAT to be accounted for by the recipient under Article 196 of Council Directive 2006/112/EC.', export: 'Supply of services outside the EU — not subject to Swedish VAT.' },
};

export const calcTotals = (items: InvoiceItem[]) => {
  const subtotal = items.reduce((s, i) => s + i.quantity * i.unit_price, 0);
  const tax = items.reduce((s, i) => s + i.quantity * i.unit_price * (i.vat_rate / 100), 0);
  return { subtotal, tax, total: subtotal + tax };
};

const money = (n: number, cur: string, lang: InvoiceLang) =>
  `${n.toLocaleString(lang === 'sv' ? 'sv-SE' : 'en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).replace(/\u00a0/g, ' ').replace(/\u2212/g, '-')} ${cur}`;
const date = (d: string, lang: InvoiceLang) =>
  new Date(d + 'T12:00:00').toLocaleDateString(lang === 'sv' ? 'sv-SE' : 'en-US', { year: 'numeric', month: 'long', day: 'numeric' });

export function buildInvoicePdf(inv: InvoiceData) {
  const t = T[inv.lang];
  const mode = vatModeFor(inv.billed_to?.country);
  inv = { ...inv, items: applyVatMode(inv.items, inv.billed_to?.country) };
  const doc = new jsPDF({ unit: 'mm', format: 'a4' });
  const { subtotal, tax, total } = calcTotals(inv.items);
  const L = 18;
  const credit = inv.kind === 'credit';
  const issuerEntity = inv.issuer_entity === 'us' ? 'us' : 'se';

  const drawFooter = () => {
    doc.setDrawColor(180).setLineWidth(0.3).line(L, 260, 210 - L, 260);
    const columns: Array<{ x: number; title: string; lines: string[] }> = [
      { x: 18, title: 'Sweden', lines: [ISSUER.street, `${ISSUER.postal} ${ISSUER.city}`, ISSUER.country,
        'Company registration number:', ISSUER.companyRegistrationNumber] },
      { x: 62, title: 'USA', lines: [ISSUER.usStreet, `${ISSUER.usPostal} ${ISSUER.usCity},`,
        `${ISSUER.usRegion}, ${ISSUER.usCountry}`, ISSUER.usEin] },
      { x: 106, title: 'Offices', lines: ['Stockholm · Dubai', 'Kyiv · Orlando', 'Delaware · Tel Aviv'] },
      { x: 150, title: 'Contact', lines: [ISSUER.email, ISSUER.website] },
    ];
    columns.forEach(({ x, title, lines }) => {
      doc.setFont('helvetica', 'bold').setFontSize(7.3).setTextColor(45).text(title, x, 266);
      doc.setFont('helvetica', 'normal').setFontSize(6.2).setTextColor(100);
      lines.forEach((line, index) => doc.text(line, x, 271 + index * 3.2));
    });
    doc.setTextColor(0);
  };


  doc.setFont('helvetica', 'bold').setFontSize(24).text(credit ? t.creditTitle : t.title, L, 25);
  doc.setFont('helvetica', 'normal').setFontSize(10);
  doc.text(`${t.number}: ${inv.invoice_number}`, L, 34);
  doc.text(`${t.issue}: ${date(inv.issue_date, inv.lang)}`, L, 39);
  doc.text(`${t.due}: ${date(inv.due_date, inv.lang)}`, L, 44);
  if (credit && inv.credited_number) doc.setFont('helvetica', 'bold').text(`${t.creditRef}: ${inv.credited_number}`, L, 49).setFont('helvetica', 'normal');

  const b = inv.billed_to;
  const billed = [b.name, b.street, [b.postal_code, b.city].filter(Boolean).join(' '), b.country, b.vat].filter(Boolean) as string[];
  const issuer = issuerEntity === 'se'
    ? [ISSUER.name, ISSUER.street, `${ISSUER.postal} ${ISSUER.city}`, ISSUER.country]
    : ['Suteki Studios Inc.', ISSUER.usStreet, `${ISSUER.usPostal} ${ISSUER.usCity}, ${ISSUER.usRegion}`, ISSUER.usCountry];
  doc.setFont('helvetica', 'bold').text(t.billed, L, 58).text(t.issued, 110, 58);
  doc.setFont('helvetica', 'normal');
  billed.forEach((l, i) => doc.text(l, L, 64 + i * 5));
  if (b.customer_ref?.trim()) {
    const refY = 64 + billed.length * 5;
    doc.setFont('helvetica', 'bold').text(`${t.customerRef}:`, L, refY);
    doc.setFont('helvetica', 'normal');
    doc.text(doc.splitTextToSize(b.customer_ref.trim(), 80), L + 28, refY);
  }
  issuer.forEach((l, i) => doc.text(l, 110, 64 + i * 5));

  doc.setFont('helvetica', 'bold').setFontSize(15)
    .text(credit ? `${t.creditAmount}: ${money(total, inv.currency, inv.lang)}`
      : `${money(total, inv.currency, inv.lang)} ${t.dueBy} ${date(inv.due_date, inv.lang)}`, L, 108);

  const showVat = mode === 'domestic';
  const m = (n: number) => money(n, inv.currency, inv.lang);
  const dueLabel = credit ? t.creditAmount : t.amountDue;
  autoTable(doc, {
    startY: 116,
    head: [showVat ? [t.product, t.qty, t.unit, t.tax, t.total] : [t.product, t.qty, t.unit, t.total]],
    body: inv.items.map((i) => showVat
      ? [i.description, String(i.quantity), m(i.unit_price), `${i.vat_rate}% ${t.vat}`, m(i.quantity * i.unit_price * (1 + i.vat_rate / 100))]
      : [i.description, String(i.quantity), m(i.unit_price), m(i.quantity * i.unit_price)]),
    foot: showVat ? [
      ['', '', '', t.exTax, m(subtotal)],
      ['', '', '', t.taxTotal, m(tax)],
      ['', '', '', dueLabel, m(total)],
    ] : [['', '', dueLabel, m(total)]],
    theme: 'plain', margin: { left: L, right: L },
    styles: { fontSize: 9, cellPadding: 2 },
    headStyles: { fontStyle: 'bold', lineWidth: { bottom: 0.3 }, lineColor: 180 },
    footStyles: { fontStyle: 'normal', halign: 'right' },
    columnStyles: { 0: { cellWidth: showVat ? 70 : 90 }, [showVat ? 4 : 3]: { halign: 'right' } },
    didParseCell: (d) => { if (d.section === 'foot' && d.row.index === (showVat ? 2 : 0)) d.cell.styles.fontStyle = 'bold'; },
  });

  let y = (doc as any).lastAutoTable.finalY + 12;
  if (mode !== 'domestic') {
    doc.setFont('helvetica', 'bold').setFontSize(9);
    const vl = doc.splitTextToSize(t[mode], 174);
    doc.text(vl, L, y); y += 6 + vl.length * 4.5;
  }
  if (inv.notes) {
    doc.setFont('helvetica', 'bold').setFontSize(10).text(t.notes, L, y);
    doc.setFont('helvetica', 'normal');
    const lines = doc.splitTextToSize(inv.notes, 170);
    doc.text(lines, L, y + 5); y += 8 + lines.length * 5;
  }
  if (credit) {
    doc.setFont('helvetica', 'normal').setFontSize(10).text(t.creditNote, L, y);
    drawFooter();
    return doc;
  }
  // Footer block is always in English, regardless of invoice language.
  const e = T.en;
  doc.setFont('helvetica', 'bold').setFontSize(12).text(e.bankTitle, L, y);
  doc.setFont('helvetica', 'normal').setFontSize(9).text(e.bankNote, L, y + 5);
  autoTable(doc, {
    startY: y + 8, theme: 'plain', margin: { left: L, right: L }, styles: { fontSize: 9, cellPadding: 1.2 },
    columnStyles: { 0: { fontStyle: 'bold', cellWidth: 64 } },
    body: [[e.ref, inv.invoice_number], ...bankRows(inv.currency, 'en')],
  });

  drawFooter();

  return doc;
}

export function generateInvoicePdf(inv: InvoiceData) {
  buildInvoicePdf(inv).save(`invoice-${inv.invoice_number}.pdf`);
}
