
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
import { StorageRecord, Customer, WorkOrder, SystemSettings, Vehicle, InventorySession, LoanerProtocol } from '../types';

const formatCurrency = (amount: number) => {
    return amount.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';
};

// Helper: Draw Checkbox
const drawCheckbox = (doc: jsPDF, x: number, y: number, checked: boolean, label: string) => {
    doc.setDrawColor(0);
    doc.setFillColor(255, 255, 255);
    doc.rect(x, y, 4, 4, 'FD');
    if (checked) {
        doc.setLineWidth(0.5);
        doc.line(x, y, x + 4, y + 4);
        doc.line(x + 4, y, x, y + 4);
    }
    doc.setFontSize(9);
    doc.text(label, x + 6, y + 3);
};

const drawHeader = (doc: jsPDF, title: string, settings: SystemSettings) => {
    const pageWidth = doc.internal.pageSize.getWidth();
    const margin = 20;
    
    // Logo Placeholder / Brand Color Line
    doc.setFillColor(settings.brandColor || '#4f46e5');
    doc.rect(0, 0, 10, doc.internal.pageSize.getHeight(), 'F'); // Sidebar stripe

    // Company Info (Right)
    doc.setFontSize(8);
    doc.setTextColor(100);
    doc.text(settings.companyName, pageWidth - margin, 20, { align: 'right' });
    doc.text(settings.address, pageWidth - margin, 24, { align: 'right' });
    doc.text(`${settings.zip} ${settings.city}`, pageWidth - margin, 28, { align: 'right' });

    // Title (Left)
    doc.setFont('helvetica', 'bold');
    doc.setFontSize(24);
    doc.setTextColor(30, 41, 59);
    doc.text(title, margin + 5, 30);
    
    doc.setDrawColor(200);
    doc.line(margin + 5, 40, pageWidth - margin, 40);
};

const drawFooter = (doc: jsPDF, settings: SystemSettings) => {
    const pageWidth = doc.internal.pageSize.getWidth();
    const pageHeight = doc.internal.pageSize.getHeight();
    const margin = 20;
    const footerY = pageHeight - 25;

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(7);
    doc.setTextColor(150);
    doc.setDrawColor(230);
    doc.line(margin, footerY - 5, pageWidth - margin, footerY - 5);

    const colWidth = (pageWidth - 2 * margin) / 4;
    
    // Col 1: Contact
    doc.text('KONTAKT', margin, footerY);
    doc.setTextColor(80);
    doc.text(settings.companyName, margin, footerY + 4);
    doc.text(settings.phone || '', margin, footerY + 8);
    doc.text(settings.email || '', margin, footerY + 12);

    // Col 2: Address
    doc.setTextColor(150);
    doc.text('ADRESSE', margin + colWidth, footerY);
    doc.setTextColor(80);
    doc.text(settings.address, margin + colWidth, footerY + 4);
    doc.text(`${settings.zip} ${settings.city}`, margin + colWidth, footerY + 8);
    doc.text(settings.website || '', margin + colWidth, footerY + 12);

    // Col 3: Bank
    doc.setTextColor(150);
    doc.text('BANKVERBINDUNG', margin + 2 * colWidth, footerY);
    doc.setTextColor(80);
    doc.text(settings.bankName || '', margin + 2 * colWidth, footerY + 4);
    doc.text(`IBAN: ${settings.iban || ''}`, margin + 2 * colWidth, footerY + 8);
    doc.text(`BIC: ${settings.bic || ''}`, margin + 2 * colWidth, footerY + 12);

    // Col 4: Legal
    doc.setTextColor(150);
    doc.text('RECHTLICHES', margin + 3 * colWidth, footerY);
    doc.setTextColor(80);
    doc.text(`St.-Nr: ${settings.taxId || ''}`, margin + 3 * colWidth, footerY + 4);
    doc.text(`USt-Id: ${settings.vatId || ''}`, margin + 3 * colWidth, footerY + 8);
    doc.text(`GF: ${settings.managingDirector || ''}`, margin + 3 * colWidth, footerY + 12);
};

export const generateStorageSlipPDF = (record: StorageRecord, customer: Customer, settings: SystemSettings) => {
  const doc = new jsPDF();
  const pageWidth = doc.internal.pageSize.getWidth();
  const margin = 25; // Adjusted margin due to sidebar
  const contentWidth = pageWidth - margin - 15;

  drawHeader(doc, 'EINLAGERUNGSBELEG', settings);

  let currentY = 50;

  // 1. Info Block (Grid Layout)
  doc.setFontSize(10);
  doc.setFont('helvetica', 'bold');
  doc.text('KUNDE', margin, currentY);
  doc.text('FAHRZEUG & LAGER', margin + 90, currentY);
  currentY += 5;

  doc.setFont('helvetica', 'normal');
  doc.setFontSize(9);
  doc.setTextColor(50);

  // Customer Data
  doc.text(`${customer.salutation} ${customer.firstName} ${customer.lastName}`, margin, currentY);
  doc.text(customer.street, margin, currentY + 5);
  doc.text(`${customer.zip} ${customer.city}`, margin, currentY + 10);
  doc.text(`Tel: ${customer.phone || '-'}`, margin, currentY + 15);
  doc.text(`Kd-Nr: ${customer.customerNumber}`, margin, currentY + 20);

  // Vehicle Data
  doc.text(`Kennzeichen:`, margin + 90, currentY);
  doc.setFont('helvetica', 'bold');
  doc.text(record.licensePlate, margin + 115, currentY);
  doc.setFont('helvetica', 'normal');
  
  doc.text(`Fahrzeug:`, margin + 90, currentY + 5);
  doc.text(`${record.vehicleManufacturer} ${record.vehicleModel}`, margin + 115, currentY + 5);
  
  doc.text(`Lagerort:`, margin + 90, currentY + 10);
  doc.setFont('helvetica', 'bold'); 
  doc.setTextColor(settings.brandColor || '#000');
  doc.text(record.location || 'NICHT ZUGEWIESEN', margin + 115, currentY + 10);
  doc.setTextColor(50);
  doc.setFont('helvetica', 'normal');

  doc.text(`Saison:`, margin + 90, currentY + 15);
  doc.text(record.season, margin + 115, currentY + 15);

  doc.text(`Datum:`, margin + 90, currentY + 20);
  doc.text(new Date(record.checkInDate).toLocaleDateString('de-DE'), margin + 115, currentY + 20);

  doc.text(`HU:`, margin + 90, currentY + 25);
  doc.text(record.nextHU || '-', margin + 115, currentY + 25);

  doc.text(`Antrieb:`, margin + 90, currentY + 30);
  doc.text(record.fuelType || '-', margin + 115, currentY + 30);

  currentY += 45;

  // 2. Tire Matrix
  doc.setFontSize(11);
  doc.setFont('helvetica', 'bold');
  doc.setTextColor(30);
  doc.text('REIFEN & ZUSTAND', margin, currentY);
  
  const tireData = [
      [
          { content: 'Position', styles: { fontStyle: 'bold' } }, 
          { content: 'VL (Vorne Links)', styles: { fontStyle: 'bold', halign: 'center' } }, 
          { content: 'VR (Vorne Rechts)', styles: { fontStyle: 'bold', halign: 'center' } },
          { content: 'HL (Hinten Links)', styles: { fontStyle: 'bold', halign: 'center' } },
          { content: 'HR (Hinten Rechts)', styles: { fontStyle: 'bold', halign: 'center' } }
      ],
      ['Profiltiefe (mm)', record.treadDepth.vl, record.treadDepth.vr, record.treadDepth.hl, record.treadDepth.hr],
      ['DOT (Alter)', record.dot, record.dot, record.dotRear || record.dot, record.dotRear || record.dot]
  ];

  autoTable(doc, {
      startY: currentY + 3,
      margin: { left: margin },
      head: [],
      body: tireData as any,
      theme: 'grid',
      styles: { fontSize: 9, cellPadding: 3, lineColor: 200, lineWidth: 0.1 },
      columnStyles: {
          0: { cellWidth: 35, fillColor: [241, 245, 249] },
          1: { halign: 'center' },
          2: { halign: 'center' },
          3: { halign: 'center' },
          4: { halign: 'center' }
      }
  });

  currentY = (doc as any).lastAutoTable.finalY + 10;

  // 3. Details Line
  doc.setFontSize(9);
  doc.text(`Reifen: ${record.manufacturer} - ${record.tireDimension} ${record.loadIndex}${record.speedIndex}`, margin, currentY);
  if(record.hasStaggeredTires) {
      currentY += 5;
      doc.text(`HA abweichend: ${record.manufacturerRear} - ${record.tireDimensionRear}`, margin, currentY);
  }
  currentY += 5;
  doc.text(`Felgen: ${record.rimType} (${record.rimsIncluded})`, margin, currentY);
  
  currentY += 10;

  // 4. Accessories & Checklist
  doc.setFontSize(11);
  doc.setFont('helvetica', 'bold');
  doc.text('ZUBEHÖR & ZUSTAND', margin, currentY);
  currentY += 6;

  const accessoriesList = record.accessories ? record.accessories.split(',') : [];
  
  drawCheckbox(doc, margin, currentY, accessoriesList.some(a => a.includes('Radbolzen')), 'Radbolzen');
  drawCheckbox(doc, margin + 40, currentY, accessoriesList.some(a => a.includes('Felgenschlösser')), 'Felgenschlösser');
  drawCheckbox(doc, margin + 80, currentY, accessoriesList.some(a => a.includes('Radkappen')), 'Radkappen');
  drawCheckbox(doc, margin + 120, currentY, accessoriesList.some(a => a.includes('Sensoren') || a.includes('RDKS')), 'RDKS Sensoren');
  
  currentY += 8;
  doc.setFontSize(9);
  doc.setFont('helvetica', 'bold');
  doc.text('Bemerkungen / Schäden:', margin, currentY);
  currentY += 5;
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(9);
  
  // Notes Box
  doc.setDrawColor(150);
  doc.rect(margin, currentY, contentWidth, 20);
  doc.text(record.notes || 'Keine sichtbaren Schäden vermerkt.', margin + 2, currentY + 5);

  currentY += 30;

  // 5. Legal & Signatures
  doc.setFontSize(7);
  doc.setTextColor(100);
  const legalText = "Der Kunde bestätigt mit seiner Unterschrift die Richtigkeit der oben genannten Angaben sowie den Erhalt der ausgelagerten Räder (bei Auslagerung) oder die Übergabe zur Einlagerung. Es gelten die allgemeinen Geschäftsbedingungen (AGB) für die Radeinlagerung. Für nicht abgeholte Räder nach Ablauf der Saison wird keine Haftung übernommen.";
  const splitLegal = doc.splitTextToSize(legalText, contentWidth);
  doc.text(splitLegal, margin, currentY);

  currentY += 20;

  doc.setDrawColor(0);
  doc.setLineWidth(0.5);
  doc.line(margin, currentY + 10, margin + 70, currentY + 10); // Sig Customer
  doc.line(margin + 90, currentY + 10, margin + 160, currentY + 10); // Sig Employee

  doc.setFontSize(8);
  doc.text("Datum, Unterschrift Kunde", margin, currentY + 14);
  doc.text(`Datum, Unterschrift ${settings.companyName}`, margin + 90, currentY + 14);

  // Footer
  doc.setFontSize(7);
  doc.setTextColor(150);
  doc.text(`Erstellt am ${new Date().toLocaleString('de-DE')} | User: ${record.checkInUser || 'System'} | ID: ${record.id}`, margin, 290);

  doc.save(`Einlagerung_${record.licensePlate}_${new Date().getFullYear()}.pdf`);
};

export const generateInventoryPDF = (session: InventorySession, records: StorageRecord[], customers: Customer[], settings: SystemSettings) => {
    const doc = new jsPDF('l', 'mm', 'a4');
    const pageWidth = doc.internal.pageSize.getWidth();
    const margin = 20;
    
    drawHeader(doc, 'INVENTUR-ERGEBNISLISTE', settings);
    
    doc.setFontSize(10);
    doc.setFont('helvetica', 'normal');
    doc.text(`Name: ${session.name}`, margin + 5, 48);
    doc.text(`Saison: ${session.season}`, margin + 5, 53);
    doc.text(`Status: ${session.status === 'closed' ? 'Abgeschlossen' : 'Offen'}`, margin + 5, 58);
    doc.text(`Ergebnis: ${session.scannedItems} von ${session.totalItems} Radsätzen erfasst (${Math.round((session.scannedItems/session.totalItems)*100)}%)`, pageWidth - margin, 58, { align: 'right' });

    const tableRows = records.map(r => {
        const c = customers.find(cust => cust.id === r.customerId);
        const isScanned = session.scannedRecordIds.includes(r.id);
        
        return [
            isScanned ? 'OK' : 'FEHLT',
            r.location || '-',
            r.licensePlate,
            c ? `${c.lastName}, ${c.firstName}` : (r.isUsedCar ? 'GW-Bestand' : 'Unbekannt'),
            `${r.vehicleManufacturer} ${r.vehicleModel}`,
            r.tireDimension,
            `${r.treadDepth.vl}/${r.treadDepth.vr}/${r.treadDepth.hl}/${r.treadDepth.hr}`,
            '' // Manuelle Bemerkung Spalte
        ];
    });

    autoTable(doc, {
        startY: 65,
        margin: { left: margin + 5, right: margin },
        head: [['Status', 'Ort', 'Kennzeichen', 'Kunde', 'Fahrzeug', 'Dimension', 'Profil (VL/VR/HL/HR)', 'Notiz']],
        body: tableRows,
        theme: 'grid',
        headStyles: { fillColor: [30, 41, 59], textColor: [255, 255, 255], fontSize: 8, fontStyle: 'bold' },
        styles: { fontSize: 7, cellPadding: 2 },
        columnStyles: {
            0: { fontStyle: 'bold', cellWidth: 15 },
            1: { fontStyle: 'bold', cellWidth: 20 },
            7: { cellWidth: 40 }
        },
        didDrawCell: (data) => {
            if (data.section === 'body' && data.column.index === 0) {
                const status = data.cell.raw;
                if (status === 'FEHLT') {
                    doc.setTextColor(220, 38, 38); // Rot für Fehlende
                } else {
                    doc.setTextColor(22, 163, 74); // Grün für OK
                }
            }
        }
    });

    doc.save(`Inventur_${session.name.replace(/\s+/g, '_')}.pdf`);
};

export const generateWorkOrderPDF = (order: WorkOrder, customer: Customer, settings: SystemSettings, vehicle?: Vehicle) => {
    const doc = new jsPDF();
    const pageWidth = doc.internal.pageSize.getWidth();
    const margin = 20;
    
    drawHeader(doc, 'WERKSTATTAUFTRAG', settings);
    
    // --- Address & Order Info ---
    doc.setFontSize(8);
    doc.setTextColor(150);
    doc.text('Auftraggeber', margin, 50);
    doc.text('Auftragsdaten', pageWidth / 2, 50);

    doc.setTextColor(30);
    doc.setFontSize(10);
    doc.setFont('helvetica', 'bold');
    doc.text(`${customer.salutation} ${customer.firstName} ${customer.lastName}`, margin, 55);
    doc.text(`Auftrags-Nr: ${order.id}`, pageWidth / 2, 55);

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(9);
    doc.text(customer.street, margin, 60);
    doc.text(`${customer.zip} ${customer.city}`, margin, 65);
    doc.text(`Tel: ${customer.phone || '-'}`, margin, 70);

    doc.text(`Datum: ${new Date(order.createdAt).toLocaleDateString('de-DE')}`, pageWidth / 2, 60);
    doc.text(`Annahme: ${order.bringInDate ? new Date(order.bringInDate).toLocaleString('de-DE') : '-'}`, pageWidth / 2, 65);
    doc.text(`Abholung: ${order.expectedDeliveryDate ? new Date(order.expectedDeliveryDate).toLocaleString('de-DE') : '-'}`, pageWidth / 2, 70);
    doc.text(`Service-Berater: ${order.createdBy || 'System'}`, pageWidth / 2, 75);

    // --- Vehicle Data (Full Width) ---
    let yPos = 85;
    const hasStorage = !!order.storageLocation;
    const boxHeight = hasStorage ? 35 : 35; // Increased to accommodate two rows
    doc.setFillColor(248, 250, 252);
    doc.rect(margin, yPos, pageWidth - 2 * margin, boxHeight, 'F');
    doc.setDrawColor(226, 232, 240);
    doc.rect(margin, yPos, pageWidth - 2 * margin, boxHeight, 'D');

    doc.setFontSize(8);
    doc.setTextColor(150);
    doc.setFont('helvetica', 'bold');
    doc.text('FAHRZEUGDATEN', margin + 5, yPos + 5);
    
    doc.setFont('helvetica', 'normal');
    const v = vehicle || (order as any);
    const manufacturer = v.manufacturer || order.manufacturer || '-';
    const model = v.model || order.model || '';
    const firstReg = v.firstRegistration || order.firstRegistration;
    const firstRegStr = firstReg ? new Date(firstReg).toLocaleDateString('de-DE') : '-';
    const fuelType = v.fuelType || order.fuelType || '-';
    const nextHU = v.nextHU || order.nextHU || '-';

    const colW = (pageWidth - 2 * margin) / 5;
    
    const addVehCol = (label: string, value: string, x: number, yOffset: number = 0) => {
        doc.setTextColor(150);
        doc.setFontSize(7);
        doc.text(label, x, yPos + 12 + yOffset);
        doc.setTextColor(30);
        doc.setFontSize(9);
        doc.setFont('helvetica', 'bold');
        doc.text(value, x, yPos + 18 + yOffset);
    };

    addVehCol('KENNZEICHEN', order.licensePlate, margin + 5);
    addVehCol('FAHRZEUG', `${manufacturer} ${model}`, margin + 5 + colW);
    addVehCol('VIN', v.vin || order.vin || '-', margin + 5 + 2 * colW);
    addVehCol('HSN / TSN', `${v.hsn || order.hsn || '----'} / ${v.tsn || order.tsn || '----'}`, margin + 5 + 3 * colW);
    addVehCol('ERSTZULASSUNG', firstRegStr, margin + 5 + 4 * colW);

    // Second Row
    addVehCol('ANTRIEB', fuelType, margin + 5, 12);
    addVehCol('NÄCHSTE HU', nextHU, margin + 5 + colW, 12);
    if (order.storageLocation) {
        addVehCol('LAGERORT REIFEN', order.storageLocation, margin + 5 + 2 * colW, 12);
    }

    yPos += boxHeight + 5;

    // --- Mechanic KM Field ---
    doc.setDrawColor(200);
    doc.rect(margin, yPos, 60, 12);
    doc.setFontSize(7);
    doc.setTextColor(150);
    doc.text('KM-STAND (AKTUELL):', margin + 2, yPos + 4);
    doc.setFontSize(10);
    doc.setTextColor(30);
    if (order.mileage) doc.text(`${order.mileage.toLocaleString()} km`, margin + 2, yPos + 10);

    // --- Table Content ---
    const tableRows: any[] = [];
    order.interventions.forEach((int, index) => {
        tableRows.push([
            { content: `${index + 1}. ${int.title.toUpperCase()}`, colSpan: 4, styles: { fillColor: [241, 245, 249], fontStyle: 'bold', textColor: [30, 41, 59] } }
        ]);
        int.tasks.forEach(t => {
            tableRows.push(['AW', t.code || '', t.name, `${Math.round(t.duration / 6)} AW`]);
        });
        if (int.textItems) {
            int.textItems.forEach(txt => {
                tableRows.push([
                    { content: 'HINWEIS', styles: { fontStyle: 'italic', textColor: [100, 116, 139] } },
                    '',
                    { content: txt.text, colSpan: 2, styles: { fontStyle: 'italic', textColor: [100, 116, 139] } }
                ]);
            });
        }
    });

    autoTable(doc, {
        startY: yPos + 18,
        margin: { left: margin, right: margin },
        head: [['Typ', 'Code/Teile-Nr.', 'Beschreibung', 'Menge/Dauer']],
        body: tableRows,
        theme: 'grid',
        headStyles: { fillColor: [30, 41, 59], textColor: [255, 255, 255], fontSize: 8, fontStyle: 'bold' },
        styles: { fontSize: 9, cellPadding: 4 }
    });

    let currentY = (doc as any).lastAutoTable.finalY + 15;

    // Additional Text from Settings
    if (settings.workOrderAdditionalText) {
        doc.setFontSize(9);
        doc.setTextColor(30);
        doc.setFont('helvetica', 'bold');
        const splitText = doc.splitTextToSize(settings.workOrderAdditionalText, pageWidth - 2 * margin);
        doc.text(splitText, margin, currentY);
        currentY += (splitText.length * 5) + 5;
    }

    // AGB Notice
    doc.setFontSize(7);
    doc.setTextColor(150);
    doc.setFont('helvetica', 'normal');
    doc.text('Es gelten unsere allgemeinen Geschäftsbedingungen (AGB). Die Arbeiten wurden nach Herstellervorgaben ausgeführt.', margin, currentY);
    currentY += 10;

    // Signature Area
    doc.setDrawColor(200);
    doc.line(margin, currentY + 15, margin + 80, currentY + 15);
    doc.line(pageWidth - margin - 80, currentY + 15, pageWidth - margin, currentY + 15);
    
    doc.setFontSize(8);
    doc.text('Ort, Datum, Unterschrift Kunde', margin, currentY + 20);
    doc.text('Annahme Werkstatt', pageWidth - margin - 80, currentY + 20);

    drawFooter(doc, settings);
    doc.save(`Werkstattauftrag_${order.licensePlate}_${order.id}.pdf`);
};

export const generateInvoicePDF = (order: WorkOrder, customer: Customer, settings: SystemSettings, vehicle?: Vehicle) => {
    const doc = new jsPDF();
    const pageWidth = doc.internal.pageSize.getWidth();
    const margin = 20;
    
    const isGutschrift = order.totalGross < 0;
    const isDuplicate = (order.printCount || 0) > 0;
    
    let title = 'RECHNUNG';
    if (isGutschrift) {
        title = isDuplicate ? 'GUTSCHRIFTSDUPLIKAT' : 'GUTSCHRIFT';
    } else if (isDuplicate) {
        title = 'RECHNUNGSDUPLIKAT';
    }
    
    drawHeader(doc, title, settings);
    
    // --- Address & Invoice Info ---
    doc.setFontSize(8);
    doc.setTextColor(150);
    doc.text('Empfänger', margin, 50);
    doc.text(isGutschrift ? 'Gutschriftsdaten' : 'Rechnungsdaten', pageWidth / 2, 50);

    const isAlternativeRecipient = !!order.invoiceAddress && !!order.invoiceAddress.name;
    const recipientName = isAlternativeRecipient ? order.invoiceAddress!.name : `${customer.salutation} ${customer.firstName} ${customer.lastName}`;
    const recipientStreet = isAlternativeRecipient ? order.invoiceAddress!.street : customer.street;
    const recipientZipCity = isAlternativeRecipient ? `${order.invoiceAddress!.zip} ${order.invoiceAddress!.city}` : `${customer.zip} ${customer.city}`;

    doc.setTextColor(30);
    doc.setFontSize(10);
    doc.setFont('helvetica', 'bold');
    doc.text(recipientName, margin, 55);
    doc.text(`${isGutschrift ? 'Gutschrifts-Nr' : 'Rechnungs-Nr'}: ${order.invoiceNumber || 'ENTWURF'}`, pageWidth / 2, 55);

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(9);
    doc.text(recipientStreet, margin, 60);
    doc.text(recipientZipCity, margin, 65);

    doc.text(`Belegdatum: ${new Date(order.completedAt || order.createdAt).toLocaleDateString('de-DE')}`, pageWidth / 2, 60);
    doc.text(`Kundennummer: ${customer.customerNumber}`, pageWidth / 2, 65);
    doc.text(`Auftrags-Ref: ${order.id}`, pageWidth / 2, 70);

    // --- Vehicle Data (Full Width) ---
    let yPos = 85;
    const hasStorage = !!order.storageLocation;
    const boxHeight = 35;
    doc.setFillColor(248, 250, 252);
    doc.rect(margin, yPos, pageWidth - 2 * margin, boxHeight, 'F');
    doc.setDrawColor(226, 232, 240);
    doc.rect(margin, yPos, pageWidth - 2 * margin, boxHeight, 'D');

    doc.setFontSize(8);
    doc.setTextColor(150);
    doc.setFont('helvetica', 'bold');
    doc.text('FAHRZEUGDATEN', margin + 5, yPos + 5);
    
    doc.setFont('helvetica', 'normal');
    const v = vehicle || (order as any);
    const manufacturer = v.manufacturer || order.manufacturer || '-';
    const model = v.model || order.model || '';
    const vin = v.vin || order.vin || '-';
    const firstReg = v.firstRegistration || order.firstRegistration;
    const firstRegStr = firstReg ? new Date(firstReg).toLocaleDateString('de-DE') : '-';
    const fuelType = v.fuelType || order.fuelType || '-';
    const nextHU = v.nextHU || order.nextHU || '-';

    const colW = (pageWidth - 2 * margin) / 5;
    
    const addVehCol = (label: string, value: string, x: number, yOffset: number = 0) => {
        doc.setTextColor(150);
        doc.setFontSize(7);
        doc.text(label, x, yPos + 12 + yOffset);
        doc.setTextColor(30);
        doc.setFontSize(9);
        doc.setFont('helvetica', 'bold');
        doc.text(value, x, yPos + 18 + yOffset);
    };

    addVehCol('KENNZEICHEN', order.licensePlate, margin + 5);
    addVehCol('FAHRZEUG', `${manufacturer} ${model}`, margin + 5 + colW);
    addVehCol('VIN', vin, margin + 5 + 2 * colW);
    addVehCol('ERSTZULASSUNG', firstRegStr, margin + 5 + 3 * colW);
    addVehCol('KM-STAND', `${(order.mileageOut || order.mileage || 0).toLocaleString()} km`, margin + 5 + 4 * colW);

    // Second Row
    addVehCol('ANTRIEB', fuelType, margin + 5, 12);
    addVehCol('NÄCHSTE HU', nextHU, margin + 5 + colW, 12);
    if (order.storageLocation) {
        addVehCol('LAGERORT REIFEN', order.storageLocation, margin + 5 + 2 * colW, 12);
    }

    yPos += boxHeight + 10;

    if (isAlternativeRecipient) {
        doc.setFontSize(9);
        doc.setTextColor(100);
        doc.text(`Auftraggeber / Leistungsempfänger: ${customer.salutation} ${customer.firstName} ${customer.lastName}, ${customer.street}, ${customer.zip} ${customer.city}`, margin, yPos);
        yPos += 10;
    }

    // Table Content
    const tableRows: any[] = [];
    order.interventions.forEach((int, index) => {
        tableRows.push([
            { content: `${index + 1}. ${int.title.toUpperCase()}`, colSpan: 7, styles: { fillColor: [241, 245, 249], fontStyle: 'bold', textColor: [30, 41, 59] } }
        ]);

        int.tasks.forEach(t => {
            const standardRate = settings.categoryRates[t.category] || settings.hourlyRate;
            const price = t.price !== undefined ? t.price : (t.duration / 60) * standardRate;
            const discount = t.discount || 0;
            const net = price * (1 - discount/100);

            tableRows.push([
                'AW',
                t.code || '',
                t.name,
                Math.round(t.duration / 6).toString(), 
                formatCurrency(price),
                discount > 0 ? `-${discount}%` : '',
                formatCurrency(net)
            ]);
        });

        int.additionalItems.forEach(i => {
            const itemTotal = i.quantity * i.pricePerUnit;
            const discount = i.discount || 0;
            const net = itemTotal * (1 - discount/100);

            tableRows.push([
                'TEIL',
                i.articleNumber || '',
                i.name,
                i.quantity.toString(),
                formatCurrency(i.pricePerUnit),
                discount > 0 ? `-${discount}%` : '',
                formatCurrency(net)
            ]);
        });

        if (int.textItems) {
            int.textItems.forEach(txt => {
                tableRows.push([
                    { content: 'HINWEIS', styles: { fontStyle: 'italic', textColor: [100, 116, 139] } },
                    '',
                    { content: txt.text, colSpan: 5, styles: { fontStyle: 'italic', textColor: [100, 116, 139] } }
                ]);
            });
        }
    });

    autoTable(doc, {
        startY: yPos,
        margin: { left: margin, right: margin },
        head: [['Typ', 'Code/Teile-Nr.', 'Beschreibung', 'Menge', 'E-Preis', 'Rabatt', 'Gesamt']],
        body: tableRows,
        theme: 'grid',
        headStyles: { fillColor: [30, 41, 59], textColor: [255, 255, 255], fontSize: 8, fontStyle: 'bold' },
        styles: { fontSize: 8, cellPadding: 3 }
    });

    // Totals logic
    let subtotal = 0;
    order.interventions.forEach(int => {
        int.tasks.forEach(t => {
            const r = settings.categoryRates[t.category] || settings.hourlyRate;
            const p = t.price !== undefined ? t.price : (t.duration / 60) * r;
            subtotal += p * (1 - (t.discount||0)/100);
        });
        int.additionalItems.forEach(i => {
            subtotal += (i.quantity * i.pricePerUnit) * (1 - (i.discount||0)/100);
        });
    });

    let voucherDed = 0;
    if (order.voucher) {
        if (order.voucher.type === 'fixed') voucherDed = order.voucher.amount;
        else voucherDed = subtotal * (order.voucher.amount / 100);
    }
    
    const net = Math.max(0, subtotal - voucherDed);
    const tax = net * (settings.taxRate / 100);
    const gross = net + tax;

    let currentY = (doc as any).lastAutoTable.finalY + 10;
    const totalsX = pageWidth - margin;

    doc.setFontSize(9);
    doc.text('Netto:', totalsX - 40, currentY, { align: 'right' });
    doc.text(formatCurrency(net), totalsX, currentY, { align: 'right' });
    
    currentY += 5;
    doc.text(`MwSt (${settings.taxRate}%):`, totalsX - 40, currentY, { align: 'right' });
    doc.text(formatCurrency(tax), totalsX, currentY, { align: 'right' });
    
    currentY += 10;
    doc.setFontSize(12);
    doc.setFont('helvetica', 'bold');
    doc.text('GESAMTBETRAG:', totalsX - 40, currentY, { align: 'right' });
    doc.text(formatCurrency(gross), totalsX, currentY, { align: 'right' });

    currentY += 15;
    doc.setFontSize(7);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(150);
    doc.text('Zahlbar sofort nach Rechnungserhalt ohne Abzug. Es gelten unsere allgemeinen Geschäftsbedingungen (AGB).', margin, currentY);

    drawFooter(doc, settings);
    
    let fileNamePrefix = 'Rechnung';
    if (isGutschrift) {
        fileNamePrefix = isDuplicate ? 'Gutschriftsduplikat' : 'Gutschrift';
    } else if (isDuplicate) {
        fileNamePrefix = 'Rechnungsduplikat';
    }
    
    doc.save(`${fileNamePrefix}_${order.invoiceNumber || order.id}.pdf`);
};

export const generateEstimatePDF = (order: WorkOrder, customer: Customer, settings: SystemSettings) => {
    const doc = new jsPDF();
    drawHeader(doc, 'KOSTENVORANSCHLAG', settings);
    // Reuse invoice logic layout if needed, essentially similar structure but different title
    // For brevity, we are not fully implementing the estimate layout here differently than invoice
    doc.text('Dies ist ein unverbindliches Angebot.', 20, 280);
    doc.save(`Angebot_${order.licensePlate}.pdf`);
};

export const generateOfferPDF = (record: StorageRecord, customer: Customer, offer: any, userName: string, settings: SystemSettings) => {
    const doc = new jsPDF();
    const pageWidth = doc.internal.pageSize.getWidth();
    const margin = 20;
    const rightColX = pageWidth - margin - 70;
    
    drawHeader(doc, 'REIFEN-ANGEBOT', settings);
    
    // --- Left: Address ---
    doc.setFontSize(8);
    doc.setTextColor(150);
    doc.text('Empfänger', margin, 55);
    doc.setTextColor(30);
    doc.setFontSize(10);
    doc.setFont('helvetica', 'bold');
    doc.text(`${customer.salutation} ${customer.firstName} ${customer.lastName}`, margin, 60);
    doc.setFont('helvetica', 'normal');
    doc.text(customer.street, margin, 65);
    doc.text(`${customer.zip} ${customer.city}`, margin, 70);

    // --- Right: Offer Data ---
    doc.setFontSize(10);
    doc.setFont('helvetica', 'bold');
    doc.text('ANGEBOTSDATEN', rightColX, 55);
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(9);

    let yPos = 62;
    const addLine = (label: string, value: string) => {
        doc.setTextColor(150);
        doc.text(label, rightColX, yPos);
        doc.setTextColor(30);
        doc.text(value, rightColX + 35, yPos);
        yPos += 5;
    };

    addLine('Datum:', new Date().toLocaleDateString('de-DE'));
    addLine('Kundennummer:', customer.customerNumber);
    addLine('Erstellt von:', userName);

    // --- Right: Vehicle Data ---
    yPos += 5;
    doc.setFontSize(10);
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(30);
    doc.text('FAHRZEUGDATEN', rightColX, yPos);
    doc.setFont('helvetica', 'normal');
    doc.setFontSize(9);
    yPos += 7;

    addLine('Kennzeichen:', record.licensePlate);
    addLine('Fahrzeug:', `${record.vehicleManufacturer} ${record.vehicleModel}`);

    // Table Content
    const tableRows: any[] = [];
    
    // Tires
    const tireNet = offer.pricePerTire;
    const tireTotalNet = tireNet * offer.quantity;
    
    tableRows.push([
        'REIFEN',
        offer.articleNumber || '',
        `${offer.tireName}\n${record.tireDimension} ${offer.labelFuel}/${offer.labelWet}/${offer.labelDb}dB`,
        offer.quantity.toString(),
        formatCurrency(tireNet),
        '',
        formatCurrency(tireTotalNet)
    ]);

    let subtotal = tireTotalNet;

    // Services
    if (offer.includeMounting) {
        const mountingNet = offer.priceMounting;
        const mountingTotalNet = mountingNet * offer.quantity;
        subtotal += mountingTotalNet;
        tableRows.push([
            'SERVICE',
            '',
            'Montage & Wuchten',
            offer.quantity.toString(),
            formatCurrency(mountingNet),
            '',
            formatCurrency(mountingTotalNet)
        ]);
    }

    if (offer.includeSwap) {
        const swapNet = offer.priceSwap;
        const swapTotalNet = swapNet * 1; // Swap is usually per vehicle (4 tires) or per set. Assuming price is for the set here based on typical usage, but let's check OfferCreate.tsx logic.
        // Wait, OfferCreate.tsx calculates swap as: formData.priceSwap (total for the vehicle)
        subtotal += swapTotalNet;
        tableRows.push([
            'SERVICE',
            '',
            'Radwechsel (Fahrzeug)',
            '1',
            formatCurrency(swapNet),
            '',
            formatCurrency(swapTotalNet)
        ]);
    }

    if (offer.includeValves) {
        const valvesNet = offer.priceValves;
        const valvesTotalNet = valvesNet * offer.quantity;
        subtotal += valvesTotalNet;
        tableRows.push([
            'MATERIAL',
            '',
            'Gummiventil',
            offer.quantity.toString(),
            formatCurrency(valvesNet),
            '',
            formatCurrency(valvesTotalNet)
        ]);
    }

    if (offer.includeDisposal) {
        const disposalNet = offer.priceDisposal;
        const disposalTotalNet = disposalNet * offer.quantity;
        subtotal += disposalTotalNet;
        tableRows.push([
            'SERVICE',
            '',
            'Altreifenentsorgung',
            offer.quantity.toString(),
            formatCurrency(disposalNet),
            '',
            formatCurrency(disposalTotalNet)
        ]);
    }

    if (offer.includeStorage) {
        const storageNet = offer.priceStorage;
        const storageTotalNet = storageNet * 1; // Storage is usually per set
        subtotal += storageTotalNet;
        tableRows.push([
            'SERVICE',
            '',
            'Radeinlagerung (Saison)',
            '1',
            formatCurrency(storageNet),
            '',
            formatCurrency(storageTotalNet)
        ]);
    }

    autoTable(doc, {
        startY: 115,
        margin: { left: margin, right: margin },
        head: [['Typ', 'Code/Teile-Nr.', 'Beschreibung', 'Menge', 'E-Preis', 'Rabatt', 'Gesamt']],
        body: tableRows,
        theme: 'grid',
        headStyles: { fillColor: [30, 41, 59], textColor: [255, 255, 255], fontSize: 8, fontStyle: 'bold' },
        styles: { fontSize: 8, cellPadding: 3 }
    });

    // Discount
    let discountAmount = 0;
    if (offer.discountPercent > 0) {
        discountAmount = subtotal * (offer.discountPercent / 100);
    }

    const net = Math.max(0, subtotal - discountAmount);
    const tax = net * (settings.taxRate / 100);
    const gross = net + tax;

    let currentY = (doc as any).lastAutoTable.finalY + 10;
    const totalsX = pageWidth - margin;

    if (offer.discountPercent > 0) {
        doc.text(`Zwischensumme:`, totalsX - 40, currentY, { align: 'right' });
        doc.text(formatCurrency(subtotal), totalsX, currentY, { align: 'right' });
        currentY += 5;
        doc.text(`Rabatt (${offer.discountPercent}%):`, totalsX - 40, currentY, { align: 'right' });
        doc.text('-' + formatCurrency(discountAmount), totalsX, currentY, { align: 'right' });
        currentY += 5;
    }

    doc.text('Netto:', totalsX - 40, currentY, { align: 'right' });
    doc.text(formatCurrency(net), totalsX, currentY, { align: 'right' });
    
    currentY += 5;
    doc.text(`MwSt (${settings.taxRate}%):`, totalsX - 40, currentY, { align: 'right' });
    doc.text(formatCurrency(tax), totalsX, currentY, { align: 'right' });
    
    currentY += 10;
    doc.setFontSize(12);
    doc.setFont('helvetica', 'bold');
    doc.text('GESAMTBETRAG:', totalsX - 40, currentY, { align: 'right' });
    doc.text(formatCurrency(gross), totalsX, currentY, { align: 'right' });

    currentY += 20;
    doc.setFontSize(9);
    doc.setFont('helvetica', 'normal');
    doc.setTextColor(100);
    doc.text('Dies ist ein unverbindliches Angebot. Preise freibleibend.', margin, currentY);

    doc.save(`Reifenangebot_${record.licensePlate}.pdf`);
};

export const generateLoanerContractPDF = (customer: Customer, carInfo: string, licensePlate: string, protocol: LoanerProtocol, settings: SystemSettings) => {
    const doc = new jsPDF();
    const pageWidth = doc.internal.pageSize.getWidth();
    const margin = 20;
    const contentWidth = pageWidth - margin * 2;

    drawHeader(doc, 'MIETWAGEN-ÜBERLASSUNG', settings);

    let currentY = 55;

    // 1. Parties
    doc.setFontSize(10);
    doc.setFont('helvetica', 'bold');
    doc.text('MIETER (KUNDE)', margin, currentY);
    doc.text('FAHRZEUG (MIETOBJEKT)', pageWidth / 2 + 10, currentY);
    currentY += 6;

    doc.setFont('helvetica', 'normal');
    doc.setFontSize(9);
    doc.setTextColor(50);

    // Left Col
    doc.text(`${customer.salutation} ${customer.firstName} ${customer.lastName}`, margin, currentY);
    doc.text(customer.street, margin, currentY + 5);
    doc.text(`${customer.zip} ${customer.city}`, margin, currentY + 10);
    doc.text(`Tel: ${customer.phone || '-'}`, margin, currentY + 15);
    
    // Right Col
    doc.text(carInfo, pageWidth / 2 + 10, currentY); // e.g. "VW Golf 8"
    doc.text(`Kennzeichen: ${licensePlate}`, pageWidth / 2 + 10, currentY + 5);
    
    currentY += 25;

    // 2. Protocols
    doc.setDrawColor(200);
    doc.setLineWidth(0.5);
    doc.line(margin, currentY, pageWidth - margin, currentY);
    currentY += 10;

    doc.setFontSize(11);
    doc.setFont('helvetica', 'bold');
    doc.setTextColor(30);
    doc.text('ÜBERGABE-PROTOKOLL', margin, currentY);
    currentY += 8;

    const ho = protocol.handover;
    const rt = protocol.return;

    const data = [
        ['', 'ÜBERGABE (START)', 'RÜCKNAHME (ENDE)'],
        ['Datum / Uhrzeit', new Date(ho.date).toLocaleString('de-DE'), rt ? new Date(rt.date).toLocaleString('de-DE') : '.......................................'],
        ['KM-Stand', `${ho.mileage} km`, rt ? `${rt.mileage} km` : '.......................... km'],
        ['Tankfüllung', `${ho.fuelLevel}%`, rt ? `${rt.fuelLevel}%` : '.......................... %'],
        ['Schäden / Zustand', ho.damages || 'Keine Vorschäden', rt ? (rt.damages || 'Keine Neuschäden') : '.......................................']
    ];

    autoTable(doc, {
        startY: currentY,
        margin: { left: margin, right: margin },
        head: [['', 'ÜBERGABE (START)', 'RÜCKNAHME (ENDE)']],
        body: data.slice(1),
        theme: 'grid',
        headStyles: { fillColor: [51, 65, 85], textColor: 255, fontSize: 9, fontStyle: 'bold' },
        columnStyles: { 0: { fontStyle: 'bold', cellWidth: 40 } },
        styles: { fontSize: 9, cellPadding: 3 }
    });

    currentY = (doc as any).lastAutoTable.finalY + 15;

    // 3. Legal Text
    doc.setFontSize(8);
    doc.setFont('helvetica', 'normal');
    const terms = [
        "1. Das Fahrzeug wurde in technisch einwandfreiem Zustand übergeben. Vorhandene Schäden sind im Protokoll vermerkt.",
        "2. Der Mieter haftet für alle während der Mietdauer entstandenen Schäden, sowie für Verkehrsverstöße.",
        "3. Im Schadensfall besteht eine Selbstbeteiligung in Höhe von 1.000,00 € pro Schadensfall.",
        "4. Das Fahrzeug ist vollgetankt zurückzugeben. Fehlmengen werden zzgl. Servicegebühr berechnet.",
        "5. Rauchverbot im gesamten Fahrzeug. Bei Zuwiderhandlung wird eine Reinigungsgebühr von 150 € fällig."
    ];

    terms.forEach(term => {
        doc.text(term, margin, currentY);
        currentY += 5;
    });

    currentY += 20;

    // 4. Signatures
    doc.setFontSize(9);
    doc.setFont('helvetica', 'bold');
    doc.text('Unterschriften zur Übergabe:', margin, currentY);
    
    currentY += 20;
    doc.setDrawColor(0);
    doc.line(margin, currentY, margin + 70, currentY); // Customer
    doc.line(margin + 90, currentY, margin + 160, currentY); // Dealer

    doc.setFontSize(8);
    doc.setFont('helvetica', 'normal');
    doc.text("Mieter (Kunde)", margin, currentY + 5);
    doc.text(`Vermieter (${settings.companyName})`, margin + 90, currentY + 5);

    doc.save(`Mietvertrag_${licensePlate}_${new Date().getFullYear()}.pdf`);
};
