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

interface VoucherData {
  bookingRef: string;
  status: string;
  passengers: Array<{
    fullName: string;
    category: string;
    seat?: {
      number: string;
      coach: string;
      seatClass: string;
    };
  }>;
  schedule: {
    trainNumber: string;
    trainName?: string;
    origin: {
      name: string;
      code: string;
      city: string;
    };
    destination: {
      name: string;
      code: string;
      city: string;
    };
    departureAt: string;
    arrivalAt: string;
  };
  totalMinor: number;
  currency: string;
  bookingType: string;
  createdAt: string;
}

export const generateVoucherPDF = async (booking: VoucherData) => {
  const doc = new jsPDF({
    orientation: 'portrait',
    unit: 'mm',
    format: 'a4',
  });

  const pageWidth = doc.internal.pageSize.getWidth();
  const pageHeight = doc.internal.pageSize.getHeight();
  const margin = 15;
  let yPos = margin;

  // Colors
  const primaryColor = [20, 113, 76]; // EDR Green
  const darkGray = [51, 51, 51];
  const mediumGray = [102, 102, 102];
  const lightGray = [200, 200, 200];

  // ============ HEADER ============
  // Company branding strip
  doc.setFillColor(primaryColor[0], primaryColor[1], primaryColor[2]);
  doc.rect(0, 0, pageWidth, 30, 'F');

  // Load and add logo
  try {
    const logoImg = await fetch('/edr-logo.png');
    const logoBlob = await logoImg.blob();
    const logoDataUrl = await new Promise<string>((resolve) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result as string);
      reader.readAsDataURL(logoBlob);
    });
    
    // Create image to get dimensions
    const img = new Image();
    await new Promise((resolve) => {
      img.onload = resolve;
      img.src = logoDataUrl;
    });
    
    // Calculate aspect ratio and dimensions
    const logoHeight = 18;
    const logoWidth = (img.width / img.height) * logoHeight;
    
    // Add logo on left side with proper aspect ratio
    doc.addImage(logoDataUrl, 'PNG', margin, 6, logoWidth, logoHeight);
    
    // Company name next to logo
    doc.setTextColor(255, 255, 255);
    doc.setFontSize(20);
    doc.setFont('helvetica', 'bold');
    doc.text('ETHIO-DJIBOUTI RAILWAY', margin + logoWidth + 5, 14);
    
    doc.setFontSize(9);
    doc.setFont('helvetica', 'normal');
    doc.text('Premium Travel Experience', margin + logoWidth + 5, 20);
  } catch (error) {
    console.error('Failed to load logo:', error);
    // Fallback: just show text centered
    doc.setTextColor(255, 255, 255);
    doc.setFontSize(24);
    doc.setFont('helvetica', 'bold');
    doc.text('ETHIO-DJIBOUTI RAILWAY', pageWidth / 2, 12, { align: 'center' });
    
    doc.setFontSize(10);
    doc.setFont('helvetica', 'normal');
    doc.text('Premium Travel Experience', pageWidth / 2, 18, { align: 'center' });
  }

  yPos = 40;

  // ============ TITLE & STATUS ============
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFontSize(20);
  doc.setFont('helvetica', 'bold');
  doc.text('BOOKING VOUCHER', pageWidth / 2, yPos, { align: 'center' });

  yPos += 10;

  // Status badge (simplified)
  const statusText = booking.status === 'TICKETED' || booking.status === 'CONFIRMED' ? 'CONFIRMED' : booking.status;
  const statusColor = booking.status === 'TICKETED' || booking.status === 'CONFIRMED' ? [34, 197, 94] : [234, 179, 8];
  
  doc.setFillColor(statusColor[0], statusColor[1], statusColor[2]);
  doc.rect(pageWidth / 2 - 20, yPos - 4, 40, 8, 'F');
  doc.setTextColor(255, 255, 255);
  doc.setFontSize(9);
  doc.setFont('helvetica', 'bold');
  doc.text(statusText, pageWidth / 2, yPos + 1, { align: 'center' });

  yPos += 12;

  // ============ QR CODE ============
  // Generate QR code data URL
  const canvas = document.createElement('canvas');
  const QRCode = (await import('qrcode')).default;
  
  const qrSize = 35; // 35mm = 3.5cm
  await QRCode.toCanvas(canvas, booking.bookingRef, {
    width: 300,
    margin: 2,
    color: {
      dark: '#000000',
      light: '#FFFFFF',
    },
  });
  
  const qrDataUrl = canvas.toDataURL('image/png');
  
  // Place QR code at top-right
  const qrX = pageWidth - margin - qrSize;
  const qrY = yPos;
  
  doc.addImage(qrDataUrl, 'PNG', qrX, qrY, qrSize, qrSize);
  
  doc.setFontSize(8);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text('SCAN AT TERMINAL', qrX + qrSize / 2, qrY + qrSize + 4, { align: 'center' });

  // ============ BOOKING REFERENCE ============
  doc.setFillColor(245, 245, 245);
  doc.rect(margin, yPos, pageWidth - margin * 2 - qrSize - 5, 18, 'F');
  
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFontSize(9);
  doc.setFont('helvetica', 'normal');
  doc.text('BOOKING REFERENCE', margin + 5, yPos + 6);
  
  doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
  doc.setFontSize(18);
  doc.setFont('helvetica', 'bold');
  doc.text(booking.bookingRef, margin + 5, yPos + 14);

  yPos += 25;

  // ============ JOURNEY DETAILS ============
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFontSize(12);
  doc.setFont('helvetica', 'bold');
  doc.text('JOURNEY DETAILS', margin, yPos);
  
  yPos += 8;

  // Route box
  doc.setDrawColor(lightGray[0], lightGray[1], lightGray[2]);
  doc.setLineWidth(0.5);
  doc.rect(margin, yPos, pageWidth - margin * 2, 40);

  // Origin
  doc.setFontSize(9);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text('FROM', margin + 5, yPos + 6);
  
  doc.setFontSize(16);
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFont('helvetica', 'bold');
  doc.text(booking.schedule.origin.code, margin + 5, yPos + 14);
  
  doc.setFontSize(10);
  doc.setFont('helvetica', 'normal');
  doc.text(booking.schedule.origin.name, margin + 5, yPos + 20);
  
  doc.setFontSize(8);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.text(booking.schedule.origin.city, margin + 5, yPos + 25);

  // Departure time
  const departureDate = new Date(booking.schedule.departureAt);
  doc.setFontSize(14);
  doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
  doc.setFont('helvetica', 'bold');
  doc.text(departureDate.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }), margin + 5, yPos + 33);
  
  doc.setFontSize(8);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text(departureDate.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' }), margin + 5, yPos + 38);

  // Arrow
  doc.setDrawColor(primaryColor[0], primaryColor[1], primaryColor[2]);
  doc.setLineWidth(1);
  const arrowStartX = pageWidth / 2 - 10;
  const arrowEndX = pageWidth / 2 + 10;
  const arrowY = yPos + 20;
  
  // Draw arrow line
  doc.line(arrowStartX, arrowY, arrowEndX, arrowY);
  
  // Draw arrow head manually with lines
  doc.line(arrowEndX, arrowY, arrowEndX - 3, arrowY - 2);
  doc.line(arrowEndX, arrowY, arrowEndX - 3, arrowY + 2);

  // Destination
  const destX = pageWidth - margin - 50;
  doc.setFontSize(9);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text('TO', destX, yPos + 6);
  
  doc.setFontSize(16);
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFont('helvetica', 'bold');
  doc.text(booking.schedule.destination.code, destX, yPos + 14);
  
  doc.setFontSize(10);
  doc.setFont('helvetica', 'normal');
  doc.text(booking.schedule.destination.name, destX, yPos + 20);
  
  doc.setFontSize(8);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.text(booking.schedule.destination.city, destX, yPos + 25);

  // Arrival time
  const arrivalDate = new Date(booking.schedule.arrivalAt);
  doc.setFontSize(14);
  doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
  doc.setFont('helvetica', 'bold');
  doc.text(arrivalDate.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }), destX, yPos + 33);
  
  doc.setFontSize(8);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text(arrivalDate.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' }), destX, yPos + 38);

  yPos += 48;

  // Train info
  doc.setFillColor(250, 250, 250);
  doc.rect(margin, yPos, pageWidth - margin * 2, 12, 'F');
  
  doc.setFontSize(9);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text('TRAIN', margin + 5, yPos + 5);
  
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFont('helvetica', 'bold');
  doc.text(booking.schedule.trainNumber, margin + 5, yPos + 9);
  
  if (booking.schedule.trainName) {
    doc.setFont('helvetica', 'normal');
    doc.text(` - ${booking.schedule.trainName}`, margin + 25, yPos + 9);
  }

  yPos += 18;

  // ============ PASSENGERS ============
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFontSize(12);
  doc.setFont('helvetica', 'bold');
  doc.text('PASSENGERS', margin, yPos);
  
  yPos += 8;

  // Passenger table
  const passengerData = booking.passengers.map((p, idx) => [
    (idx + 1).toString(),
    p.fullName,
    p.category,
    p.seat?.number || '-',
    p.seat?.coach || '-',
    p.seat?.seatClass || '-',
  ]);

  autoTable(doc, {
    startY: yPos,
    head: [['#', 'Passenger Name', 'Type', 'Seat', 'Coach', 'Class']],
    body: passengerData,
    theme: 'striped',
    headStyles: {
      fillColor: [primaryColor[0], primaryColor[1], primaryColor[2]],
      textColor: [255, 255, 255],
      fontSize: 9,
      fontStyle: 'bold',
    },
    bodyStyles: {
      fontSize: 9,
      textColor: [darkGray[0], darkGray[1], darkGray[2]],
    },
    alternateRowStyles: {
      fillColor: [250, 250, 250],
    },
    margin: { left: margin, right: margin },
  });

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

  // ============ PAYMENT SUMMARY ============
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFontSize(12);
  doc.setFont('helvetica', 'bold');
  doc.text('PAYMENT SUMMARY', margin, yPos);
  
  yPos += 8;

  doc.setFillColor(250, 250, 250);
  doc.rect(margin, yPos, pageWidth - margin * 2, 20, 'F');

  doc.setFontSize(10);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text('Total Amount', margin + 5, yPos + 7);
  
  doc.setFontSize(16);
  doc.setTextColor(primaryColor[0], primaryColor[1], primaryColor[2]);
  doc.setFont('helvetica', 'bold');
  doc.text(`${booking.currency} ${(booking.totalMinor / 100).toFixed(2)}`, pageWidth - margin - 5, yPos + 7, { align: 'right' });

  doc.setFontSize(9);
  doc.setTextColor(34, 197, 94);
  doc.setFont('helvetica', 'bold');
  doc.text('✓ PAID', margin + 5, yPos + 15);

  yPos += 28;

  // ============ INSTRUCTIONS ============
  doc.setFillColor(252, 211, 77);
  doc.rect(margin, yPos, pageWidth - margin * 2, 18, 'F');
  
  doc.setFontSize(9);
  doc.setTextColor(darkGray[0], darkGray[1], darkGray[2]);
  doc.setFont('helvetica', 'bold');
  doc.text('⚠ IMPORTANT INSTRUCTIONS', margin + 5, yPos + 6);
  
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(8);
  doc.text('• Present this voucher at the terminal for boarding', margin + 5, yPos + 11);
  doc.text('• Arrive at least 30 minutes before departure', margin + 5, yPos + 15);

  // ============ FOOTER ============
  const footerY = pageHeight - 25;
  
  doc.setDrawColor(lightGray[0], lightGray[1], lightGray[2]);
  doc.line(margin, footerY, pageWidth - margin, footerY);
  
  doc.setFontSize(8);
  doc.setTextColor(mediumGray[0], mediumGray[1], mediumGray[2]);
  doc.setFont('helvetica', 'normal');
  doc.text('Support: support@edr.com | +251-11-XXX-XXXX', pageWidth / 2, footerY + 5, { align: 'center' });
  doc.text('Terms & Conditions apply. Visit www.edr.com for details.', pageWidth / 2, footerY + 9, { align: 'center' });
  
  doc.setFontSize(7);
  doc.text(`Generated: ${new Date().toLocaleString('en-US')}`, pageWidth / 2, footerY + 13, { align: 'center' });

  // Watermark (removed rotation as it may cause issues)
  doc.setTextColor(240, 240, 240);
  doc.setFontSize(50);
  doc.setFont('helvetica', 'bold');
  doc.text('EDR', pageWidth / 2, pageHeight / 2, { align: 'center' });

  // Save PDF
  doc.save(`EDR-Voucher-${booking.bookingRef}.pdf`);
};
