// PDF Generation Utilities for Deliveries Export
// Uses html2canvas and jspdf for client-side PDF generation

export interface DeliveryRecord {
  id: number;
  delivery_date: string;
  recorded_at?: string;
  school_name: string;
  commodity_name: string;
  supplier_name?: string;
  supplier_contact?: string;
  supplier_phone?: string;
  supplier_email?: string;
  supplier_address?: string;
  user_name: string;
  actual_quantity: number;
  notes?: string;
  review_status?: string;
  is_flagged?: boolean;
}

export interface PDFGeneratorOptions {
  title: string;
  subtitle?: string;
  includeTimestamp?: boolean;
  orientation?: 'portrait' | 'landscape';
  pageSize?: 'a4' | 'letter';
}

export function formatDate(date: string | Date): string {
  const d = new Date(date);
  return d.toLocaleDateString('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric'
  });
}

export function formatDateTime(date: string | Date): string {
  const d = new Date(date);
  return d.toLocaleString('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
}

export function formatNumber(num: number): string {
  return new Intl.NumberFormat('en-GH').format(num);
}

// Generate HTML for the deliveries table PDF
export function generateDeliveriesTableHTML(
  deliveries: DeliveryRecord[],
  options: PDFGeneratorOptions
): string {
  const timestamp = new Date().toLocaleString('en-GB', {
    dateStyle: 'full',
    timeStyle: 'short'
  });

  const totalQuantity = deliveries.reduce((sum, d) => sum + d.actual_quantity, 0);
  const approvedCount = deliveries.filter(d => d.review_status === 'APPROVED' || (!d.is_flagged && d.review_status !== 'PENDING_REVIEW')).length;
  const pendingCount = deliveries.filter(d => d.review_status === 'PENDING_REVIEW' || d.is_flagged).length;

  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Segoe UI', Arial, sans-serif;
      font-size: 10px;
      color: #1a202c;
      line-height: 1.4;
      padding: 40px;
      background: white;
    }
    
    .header {
      text-align: center;
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 3px solid #10b981;
    }
    
    .logo-section {
      margin-bottom: 15px;
    }
    
    .logo-text {
      font-size: 28px;
      font-weight: 800;
      color: #10b981;
      letter-spacing: -1px;
    }
    
    .logo-subtitle {
      font-size: 11px;
      color: #64748b;
      text-transform: uppercase;
      letter-spacing: 2px;
    }
    
    .report-title {
      font-size: 18px;
      font-weight: 700;
      color: #1e293b;
      margin: 15px 0 5px;
    }
    
    .report-meta {
      font-size: 10px;
      color: #64748b;
    }
    
    .summary-cards {
      display: flex;
      gap: 20px;
      margin-bottom: 25px;
    }
    
    .summary-card {
      flex: 1;
      background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
      border: 1px solid #bbf7d0;
      border-radius: 8px;
      padding: 15px;
      text-align: center;
    }
    
    .summary-card.pending {
      background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
      border-color: #fcd34d;
    }
    
    .summary-card.total {
      background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
      border-color: #93c5fd;
    }
    
    .summary-value {
      font-size: 24px;
      font-weight: 800;
      color: #10b981;
    }
    
    .summary-card.pending .summary-value { color: #d97706; }
    .summary-card.total .summary-value { color: #3b82f6; }
    
    .summary-label {
      font-size: 9px;
      text-transform: uppercase;
      letter-spacing: 1px;
      color: #64748b;
      margin-top: 5px;
    }
    
    table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 30px;
      font-size: 9px;
    }
    
    thead {
      background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
    }
    
    th {
      padding: 12px 8px;
      text-align: left;
      font-weight: 600;
      color: white;
      text-transform: uppercase;
      font-size: 8px;
      letter-spacing: 0.5px;
    }
    
    th:last-child, td:last-child {
      text-align: right;
    }
    
    tbody tr {
      border-bottom: 1px solid #e2e8f0;
    }
    
    tbody tr:nth-child(even) {
      background: #f8fafc;
    }
    
    tbody tr:hover {
      background: #f1f5f9;
    }
    
    td {
      padding: 10px 8px;
      vertical-align: top;
    }
    
    .status-badge {
      display: inline-block;
      padding: 3px 8px;
      border-radius: 12px;
      font-size: 8px;
      font-weight: 600;
      text-transform: uppercase;
    }
    
    .status-ok {
      background: #dcfce7;
      color: #166534;
    }
    
    .status-pending {
      background: #fef3c7;
      color: #92400e;
    }
    
    .quantity {
      font-weight: 700;
      color: #10b981;
      font-size: 11px;
    }
    
    .footer {
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #e2e8f0;
      text-align: center;
      color: #94a3b8;
      font-size: 8px;
    }
    
    .footer-brand {
      font-weight: 700;
      color: #10b981;
    }
    
    .page-number {
      position: fixed;
      bottom: 20px;
      right: 40px;
      font-size: 9px;
      color: #94a3b8;
    }
  </style>
</head>
<body>
  <div class="header">
    <div class="logo-section">
      <div class="logo-text">MONRITA</div>
      <div class="logo-subtitle">Supply Chain Management System</div>
    </div>
    <div class="report-title">${options.title}</div>
    ${options.subtitle ? `<div class="report-meta">${options.subtitle}</div>` : ''}
    <div class="report-meta">Generated: ${timestamp}</div>
  </div>
  
  <div class="summary-cards">
    <div class="summary-card">
      <div class="summary-value">${approvedCount}</div>
      <div class="summary-label">Approved Deliveries</div>
    </div>
    <div class="summary-card pending">
      <div class="summary-value">${pendingCount}</div>
      <div class="summary-label">Pending Review</div>
    </div>
    <div class="summary-card total">
      <div class="summary-value">${formatNumber(totalQuantity)}</div>
      <div class="summary-label">Total Quantity</div>
    </div>
  </div>
  
  <table>
    <thead>
      <tr>
        <th style="width: 8%">#</th>
        <th style="width: 10%">Date</th>
        <th style="width: 20%">School</th>
        <th style="width: 15%">Commodity</th>
        <th style="width: 15%">Supplier</th>
        <th style="width: 12%">User</th>
        <th style="width: 10%">Status</th>
        <th style="width: 10%">Qty</th>
      </tr>
    </thead>
    <tbody>
      ${deliveries.map((d, i) => {
        const isPending = d.review_status === 'PENDING_REVIEW' || d.is_flagged;
        return `
          <tr>
            <td>${i + 1}</td>
            <td>${formatDate(d.delivery_date)}</td>
            <td>${d.school_name}</td>
            <td>${d.commodity_name}</td>
            <td>${d.supplier_name || '-'}</td>
            <td>${d.user_name}</td>
            <td>
              <span class="status-badge ${isPending ? 'status-pending' : 'status-ok'}">
                ${isPending ? 'Pending' : 'OK'}
              </span>
            </td>
            <td class="quantity">${formatNumber(d.actual_quantity)}</td>
          </tr>
        `;
      }).join('')}
    </tbody>
  </table>
  
  <div class="footer">
    <p>This report was generated by <span class="footer-brand">Monrita</span> Supply Chain Management System</p>
    <p>Total Records: ${deliveries.length} | Report Date: ${timestamp}</p>
    <p>© ${new Date().getFullYear()} Ghana Cocoa Board - Free SHS Programme</p>
  </div>
</body>
</html>
  `;
}

// Generate HTML for individual delivery PDF
export function generateIndividualDeliveryHTML(
  delivery: DeliveryRecord,
  options: PDFGeneratorOptions
): string {
  const timestamp = new Date().toLocaleString('en-GB', {
    dateStyle: 'full',
    timeStyle: 'short'
  });
  
  const isPending = delivery.review_status === 'PENDING_REVIEW' || delivery.is_flagged;

  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Segoe UI', Arial, sans-serif;
      font-size: 11px;
      color: #1a202c;
      line-height: 1.5;
      padding: 50px;
      background: white;
    }
    
    .document {
      max-width: 700px;
      margin: 0 auto;
    }
    
    .header {
      text-align: center;
      margin-bottom: 40px;
      padding-bottom: 25px;
      border-bottom: 4px solid #10b981;
      position: relative;
    }
    
    .header::after {
      content: '';
      position: absolute;
      bottom: -4px;
      left: 50%;
      transform: translateX(-50%);
      width: 100px;
      height: 4px;
      background: #059669;
    }
    
    .logo-text {
      font-size: 36px;
      font-weight: 800;
      color: #10b981;
      letter-spacing: -1px;
    }
    
    .logo-subtitle {
      font-size: 12px;
      color: #64748b;
      text-transform: uppercase;
      letter-spacing: 3px;
      margin-top: 5px;
    }
    
    .document-title {
      font-size: 22px;
      font-weight: 700;
      color: #1e293b;
      margin: 25px 0 10px;
    }
    
    .document-number {
      font-size: 14px;
      color: #10b981;
      font-weight: 600;
    }
    
    .status-banner {
      display: inline-block;
      padding: 8px 20px;
      border-radius: 20px;
      font-weight: 700;
      text-transform: uppercase;
      font-size: 11px;
      letter-spacing: 1px;
      margin-top: 15px;
    }
    
    .status-ok {
      background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
      color: #166534;
      border: 2px solid #22c55e;
    }
    
    .status-pending {
      background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
      color: #92400e;
      border: 2px solid #f59e0b;
    }
    
    .section {
      margin-bottom: 30px;
    }
    
    .section-title {
      font-size: 13px;
      font-weight: 700;
      color: #1e293b;
      text-transform: uppercase;
      letter-spacing: 1px;
      padding-bottom: 10px;
      border-bottom: 2px solid #e2e8f0;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .section-icon {
      width: 24px;
      height: 24px;
      background: #10b981;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 12px;
    }
    
    .info-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
    }
    
    .info-item {
      background: #f8fafc;
      padding: 15px;
      border-radius: 8px;
      border-left: 4px solid #10b981;
    }
    
    .info-label {
      font-size: 9px;
      text-transform: uppercase;
      letter-spacing: 1px;
      color: #64748b;
      margin-bottom: 5px;
    }
    
    .info-value {
      font-size: 14px;
      font-weight: 600;
      color: #1e293b;
    }
    
    .info-value.highlight {
      color: #10b981;
      font-size: 20px;
    }
    
    .full-width {
      grid-column: 1 / -1;
    }
    
    .notes-box {
      background: #fefce8;
      border: 1px solid #fde047;
      border-radius: 8px;
      padding: 15px;
      margin-top: 10px;
    }
    
    .notes-title {
      font-weight: 600;
      color: #854d0e;
      margin-bottom: 8px;
    }
    
    .notes-content {
      color: #713f12;
      font-style: italic;
    }
    
    .supplier-card {
      background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%);
      border: 1px solid #bbf7d0;
      border-radius: 12px;
      padding: 20px;
    }
    
    .supplier-name {
      font-size: 16px;
      font-weight: 700;
      color: #166534;
      margin-bottom: 10px;
    }
    
    .supplier-details {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 10px;
      font-size: 10px;
    }
    
    .supplier-detail {
      display: flex;
      gap: 5px;
    }
    
    .supplier-label {
      color: #64748b;
    }
    
    .supplier-value {
      color: #1e293b;
      font-weight: 500;
    }
    
    .footer {
      margin-top: 50px;
      padding-top: 25px;
      border-top: 2px solid #e2e8f0;
      text-align: center;
    }
    
    .footer-brand {
      font-size: 14px;
      font-weight: 700;
      color: #10b981;
      margin-bottom: 10px;
    }
    
    .footer-text {
      font-size: 9px;
      color: #94a3b8;
      line-height: 1.8;
    }
    
    .signature-section {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 50px;
      margin: 40px 0;
    }
    
    .signature-box {
      text-align: center;
    }
    
    .signature-line {
      border-top: 1px solid #cbd5e1;
      margin-bottom: 8px;
      margin-top: 50px;
    }
    
    .signature-label {
      font-size: 10px;
      color: #64748b;
    }
  </style>
</head>
<body>
  <div class="document">
    <div class="header">
      <div class="logo-text">MONRITA</div>
      <div class="logo-subtitle">Supply Chain Management System</div>
      <div class="document-title">Delivery Receipt</div>
      <div class="document-number">Reference: DEL-${String(delivery.id).padStart(6, '0')}</div>
      <div class="status-banner ${isPending ? 'status-pending' : 'status-ok'}">
        ${isPending ? '⏳ Pending Review' : '✓ Verified'}
      </div>
    </div>
    
    <div class="section">
      <div class="section-title">
        <span class="section-icon">📦</span>
        Delivery Information
      </div>
      <div class="info-grid">
        <div class="info-item">
          <div class="info-label">Delivery Date</div>
          <div class="info-value">${formatDate(delivery.delivery_date)}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Recorded At</div>
          <div class="info-value">${delivery.recorded_at ? formatDateTime(delivery.recorded_at) : '-'}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Commodity</div>
          <div class="info-value">${delivery.commodity_name}</div>
        </div>
        <div class="info-item">
          <div class="info-label">Quantity Delivered</div>
          <div class="info-value highlight">${formatNumber(delivery.actual_quantity)}</div>
        </div>
        <div class="info-item full-width">
          <div class="info-label">School / Destination</div>
          <div class="info-value">${delivery.school_name}</div>
        </div>
        <div class="info-item full-width">
          <div class="info-label">Recorded By</div>
          <div class="info-value">${delivery.user_name}</div>
        </div>
      </div>
      ${delivery.notes ? `
        <div class="notes-box">
          <div class="notes-title">📝 Additional Notes</div>
          <div class="notes-content">${delivery.notes}</div>
        </div>
      ` : ''}
    </div>
    
    <div class="section">
      <div class="section-title">
        <span class="section-icon">🏢</span>
        Supplier Information
      </div>
      ${delivery.supplier_name ? `
        <div class="supplier-card">
          <div class="supplier-name">${delivery.supplier_name}</div>
          <div class="supplier-details">
            ${delivery.supplier_contact ? `
              <div class="supplier-detail">
                <span class="supplier-label">Contact:</span>
                <span class="supplier-value">${delivery.supplier_contact}</span>
              </div>
            ` : ''}
            ${delivery.supplier_phone ? `
              <div class="supplier-detail">
                <span class="supplier-label">Phone:</span>
                <span class="supplier-value">${delivery.supplier_phone}</span>
              </div>
            ` : ''}
            ${delivery.supplier_email ? `
              <div class="supplier-detail">
                <span class="supplier-label">Email:</span>
                <span class="supplier-value">${delivery.supplier_email}</span>
              </div>
            ` : ''}
            ${delivery.supplier_address ? `
              <div class="supplier-detail full-width">
                <span class="supplier-label">Address:</span>
                <span class="supplier-value">${delivery.supplier_address}</span>
              </div>
            ` : ''}
          </div>
        </div>
      ` : `
        <div class="info-item">
          <div class="info-value" style="color: #94a3b8; font-style: italic;">No supplier information linked to this delivery.</div>
        </div>
      `}
    </div>
    
    <div class="signature-section">
      <div class="signature-box">
        <div class="signature-line"></div>
        <div class="signature-label">Authorized Signature</div>
      </div>
      <div class="signature-box">
        <div class="signature-line"></div>
        <div class="signature-label">Date & Official Stamp</div>
      </div>
    </div>
    
    <div class="footer">
      <div class="footer-brand">MONRITA Supply Chain Management</div>
      <div class="footer-text">
        This document was automatically generated by the Monrita system.<br>
        Generated: ${timestamp}<br>
        © ${new Date().getFullYear()} Ghana Cocoa Board - Free Senior High School Programme
      </div>
    </div>
  </div>
</body>
</html>
  `;
}
