import type { Form } from "@shared/schema";

export async function generateFormHTML(form: Form): Promise<string> {
  try {
    const htmlContent = generateFormHTMLContent(form);
    return htmlContent;
  } catch (error) {
    console.error('Error generating HTML:', error);
    throw new Error('خطا در تولید فایل');
  }
}

function generateFormHTMLContent(form: Form): string {
  const persianDate = form.createdAt ? new Intl.DateTimeFormat('fa-IR').format(new Date(form.createdAt)) : '-';
  const departmentNames: { [key: string]: string } = {
    engineering: 'مهندسی',
    planning: 'برنامه‌ریزی', 
    commercial: 'بازرگانی',
    quality: 'کیفیت',
    financial: 'مالی',
    laboratory: 'آزمایشگاه',
    warehouse: 'انبار',
    archived: 'آرشیو'
  };

  return `
    <!DOCTYPE html>
    <html dir="rtl" lang="fa">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>فرم ${(form as any).indicatorNumber || form.formNumber}</title>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Vazir:wght@300;400;500;600;700&display=swap');
        
        * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
        }
        
        body {
          font-family: 'Vazir', Arial, sans-serif;
          font-size: 12px;
          line-height: 1.6;
          color: #333;
          direction: rtl;
          text-align: right;
        }
        
        .header {
          text-align: center;
          border-bottom: 2px solid #2563eb;
          padding-bottom: 20px;
          margin-bottom: 30px;
        }
        
        .header h1 {
          font-size: 24px;
          font-weight: 700;
          color: #1e40af;
          margin-bottom: 10px;
        }
        
        .header h2 {
          font-size: 18px;
          font-weight: 500;
          color: #374151;
        }
        
        .form-info {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 20px;
          margin-bottom: 30px;
          background-color: #f9fafb;
          padding: 20px;
          border-radius: 8px;
          border: 1px solid #e5e7eb;
        }
        
        .info-item {
          display: flex;
          justify-content: space-between;
        }
        
        .info-label {
          font-weight: 600;
          color: #374151;
        }
        
        .info-value {
          color: #6b7280;
        }
        
        .status-badge {
          padding: 4px 12px;
          border-radius: 9999px;
          font-weight: 500;
          font-size: 11px;
        }
        
        .status-archived {
          background-color: #f3f4f6;
          color: #374151;
        }
        
        .status-completed {
          background-color: #dcfce7;
          color: #166534;
        }
        
        .section {
          margin-bottom: 30px;
          border: 1px solid #e5e7eb;
          border-radius: 8px;
          overflow: hidden;
        }
        
        .section-header {
          background: linear-gradient(135deg, #3b82f6, #1d4ed8);
          color: white;
          padding: 15px 20px;
          font-weight: 600;
          font-size: 14px;
        }
        
        .section-content {
          padding: 20px;
        }
        
        .field-row {
          display: grid;
          grid-template-columns: 1fr 1fr 1fr;
          gap: 20px;
          margin-bottom: 15px;
        }
        
        .field {
          display: flex;
          flex-direction: column;
          gap: 5px;
        }
        
        .field-label {
          font-weight: 600;
          color: #374151;
          font-size: 11px;
        }
        
        .field-value {
          color: #6b7280;
          padding: 8px;
          background-color: #f9fafb;
          border-radius: 4px;
          border: 1px solid #e5e7eb;
          min-height: 36px;
          display: flex;
          align-items: center;
        }
        
        .signature-section {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 15px;
          margin-top: 20px;
        }
        
        .signature-box {
          border: 1px solid #d1d5db;
          border-radius: 6px;
          padding: 15px;
          background-color: #f9fafb;
        }
        
        .signature-title {
          font-weight: 600;
          font-size: 11px;
          color: #374151;
          margin-bottom: 8px;
        }
        
        .signature-content {
          color: #059669;
          font-weight: 500;
          font-size: 12px;
        }
        
        .signature-image {
          margin-top: 8px;
        }
        
        .signature-image img {
          max-width: 80px;
          max-height: 40px;
          border-radius: 4px;
        }
        
        .footer {
          margin-top: 40px;
          text-align: center;
          padding-top: 20px;
          border-top: 1px solid #e5e7eb;
          color: #6b7280;
          font-size: 11px;
        }
        
        table {
          width: 100%;
          border-collapse: collapse;
          margin: 15px 0;
        }
        
        th, td {
          border: 1px solid #ddd;
          padding: 8px;
          text-align: center;
        }
        
        th {
          background-color: #f5f5f5;
          font-weight: 600;
        }

        h4 {
          margin: 20px 0 10px 0;
          font-weight: 600;
          color: #374151;
        }
      </style>
    </head>
    <body>
      <div class="header">
        <h1>فرم تامین نمونه کالا</h1>
        <h2>${(form as any).indicatorNumber || form.formNumber}</h2>
      </div>

      <div class="form-info">
        <div class="info-item">
          <span class="info-label">شماره فرم:</span>
          <span class="info-value">${form.formNumber}</span>
        </div>

        <div class="info-item">
          <span class="info-label">تاریخ ایجاد:</span>
          <span class="info-value">${persianDate}</span>
        </div>

        <div class="info-item">
          <span class="info-label">وضعیت:</span>
          <span class="status-badge ${form.currentDepartment === 'archived' ? 'status-archived' : 'status-completed'}">
            ${form.currentDepartment === 'archived' ? 'آرشیو شده' : departmentNames[form.currentDepartment] || form.currentDepartment}
          </span>
        </div>
      </div>

      ${generateBasicFormContent(form)}
      
      <div class="footer">
        <p>این فرم در تاریخ ${new Intl.DateTimeFormat('fa-IR', { 
          year: 'numeric', 
          month: 'long', 
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit'
        }).format(new Date())} تولید شده است.</p>
      </div>
    </body>
    </html>
  `;
}

function generateBasicFormContent(form: Form): string {
  return `
    <!-- بخش مهندسی -->
    <div class="section">
      <div class="section-header">🔧 بخش مهندسی</div>
      <div class="section-content">
        <div class="field-row">
          <div class="field">
            <div class="field-label">نام محصول</div>
            <div class="field-value">${(form as any).productName || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره اندیکاتور</div>
            <div class="field-value">${(form as any).indicatorNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره اندیکاتور فرم قبلی</div>
            <div class="field-value">${(form as any).previousFormIndicator || '-'}</div>
          </div>
        </div>
        
        <div class="field-row">
          <div class="field">
            <div class="field-label">کد نقشه</div>
            <div class="field-value">${(form as any).drawingCode || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">فاز تکوین محصول جدید</div>
            <div class="field-value">${(form as any).newProductDevPhase || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">کد مرکز هزینه پروژه</div>
            <div class="field-value">${(form as any).projectCostCenterCode || '-'}</div>
          </div>
        </div>
        
        <div class="field-row">
          <div class="field">
            <div class="field-label">تامین کننده پیشنهادی</div>
            <div class="field-value">${(form as any).suggestedSupplier || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">مجری تامین</div>
            <div class="field-value">${(form as any).supplyExecutive || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">مدارک ارسالی</div>
            <div class="field-value">${(form as any).sentDocuments || '-'}</div>
          </div>
        </div>
        
        <div class="field-row">
          <div class="field">
            <div class="field-label">تاریخ ارسال مدارک</div>
            <div class="field-value">${(form as any).documentSendDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ نیاز</div>
            <div class="field-value">${(form as any).needDate || '-'}</div>
          </div>
        </div>
        
        <div class="field-row">
          <div class="field">
            <div class="field-label">شماره اقدام</div>
            <div class="field-value">${(form as any).actionNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ</div>
            <div class="field-value">${(form as any).engineeringDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">علت صدور</div>
            <div class="field-value">${(form as any).issueReason || '-'}</div>
          </div>
        </div>

        <div class="field-row">
          <div class="field">
            <div class="field-label">مرتبه تامین</div>
            <div class="field-value">${(form as any).supplyOrder || '-'}</div>
          </div>
        </div>
        
        ${generatePartsTable((form as any).partsTable)}
        
        <h4>تاییدات مهندسی</h4>
        <div class="signature-section">
          ${(form as any).expertApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید کارشناس مهندسی</div>
              <div class="signature-content">${(form as any).expertApproval}</div>
              ${(form as any).expertApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).expertApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
          ${(form as any).managerApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید مدیر مهندسی</div>
              <div class="signature-content">${(form as any).managerApproval}</div>
              ${(form as any).managerApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).managerApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
        </div>
      </div>
    </div>
    
    <!-- بخش برنامه‌ریزی -->
    <div class="section">
      <div class="section-header">📋 بخش برنامه‌ریزی</div>
      <div class="section-content">
        <div class="field-row">
          <div class="field">
            <div class="field-label">تاریخ انجام</div>
            <div class="field-value">${(form as any).planningExecutionDate || '-'}</div>
          </div>
        </div>
        
        ${generateMonitoringTable((form as any).planningMonitoringTable)}
        
        <h4>تاییدات برنامه‌ریزی</h4>
        <div class="signature-section">
          ${(form as any).planningExpertApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید سرپرست/کارشناس برنامه‌ریزی</div>
              <div class="signature-content">${(form as any).planningExpertApproval}</div>
              ${(form as any).planningExpertApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).planningExpertApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
        </div>
      </div>
    </div>
    
    <!-- بخش بازرگانی -->
    <div class="section">
      <div class="section-header">💼 بخش بازرگانی</div>
      <div class="section-content">
        <div class="field-row">
          <div class="field">
            <div class="field-label">نام/کد تامین کننده</div>
            <div class="field-value">${(form as any).commercialSupplierNameCode || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ ارسال نمونه</div>
            <div class="field-value">${(form as any).commercialSampleSendDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره بارنامه</div>
            <div class="field-value">${(form as any).commercialBillNumber || '-'}</div>
          </div>
        </div>
        <div class="field-row">
          <div class="field">
            <div class="field-label">کد محموله</div>
            <div class="field-value">${(form as any).commercialShipmentCode || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">گواهی پیمانکار</div>
            <div class="field-value">${(form as any).commercialContractorCertificate || '-'}</div>
          </div>
        </div>
        
        ${generateReceivedAmountsTable((form as any).commercialReceivedTable)}
        
        <h4>تاییدات بازرگانی</h4>
        <div class="signature-section">
          ${(form as any).commercialExpertApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید کارشناس بازرگانی</div>
              <div class="signature-content">${(form as any).commercialExpertApproval}</div>
              ${(form as any).commercialExpertApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).commercialExpertApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
          ${(form as any).commercialManagerApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید مدیر بازرگانی</div>
              <div class="signature-content">${(form as any).commercialManagerApproval}</div>
              ${(form as any).commercialManagerApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).commercialManagerApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
        </div>
      </div>
    </div>
    
    <!-- بخش کیفیت -->
    <div class="section">
      <div class="section-header">✅ بخش کیفیت</div>
      <div class="section-content">
        <div class="field-row">
          <div class="field">
            <div class="field-label">تاریخ انجام</div>
            <div class="field-value">${(form as any).qualityExecutionDate || '-'}</div>
          </div>
        </div>
        
        ${generateQualityPartsTable((form as any).qualityPartsTable)}
        
        <h4>تاییدات کیفیت</h4>
        <div class="signature-section">
          ${(form as any).qualityManagerApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید مدیر/جانشین کیفیت</div>
              <div class="signature-content">${(form as any).qualityManagerApproval}</div>
              ${(form as any).qualityManagerApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).qualityManagerApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
        </div>
      </div>
    </div>
    
    <!-- بخش مالی -->
    <div class="section">
      <div class="section-header">💰 بخش مالی</div>
      <div class="section-content">
        <div class="field-row">
          <div class="field">
            <div class="field-label">تاریخ انجام</div>
            <div class="field-value">${(form as any).financialExecutionDate || '-'}</div>
          </div>
        </div>
        
        ${generateCodeRegistrationTable((form as any).financialCodeTable)}
        
        <h4>تاییدات مالی</h4>
        <div class="signature-section">
          ${(form as any).financialExpertApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید کارشناس/سرپرست مالی</div>
              <div class="signature-content">${(form as any).financialExpertApproval}</div>
              ${(form as any).financialExpertApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).financialExpertApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
        </div>
      </div>
    </div>
    
    <!-- بخش آزمایشگاه -->
    <div class="section">
      <div class="section-header">🔬 بخش آزمایشگاه</div>
      <div class="section-content">
        <div class="field-row">
          <div class="field">
            <div class="field-label">شرایط خاص نگهداری</div>
            <div class="field-value">${(form as any).laboratorySpecialStorageConditions || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ انجام</div>
            <div class="field-value">${(form as any).laboratoryExecutionDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">وضعیت نهایی قطعه</div>
            <div class="field-value">${(form as any).laboratoryFinalStatus || '-'}</div>
          </div>
        </div>
        
        ${generateTestsTable((form as any).laboratoryTestsTable)}
        
        ${generatePartsStatusTable((form as any).laboratoryPartsStatusTable)}
        
        <h4>تاییدات آزمایشگاه</h4>
        <div class="signature-section">
          ${(form as any).laboratoryExpertApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید کارشناس آزمایشگاه</div>
              <div class="signature-content">${(form as any).laboratoryExpertApproval}</div>
              ${(form as any).laboratoryExpertApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).laboratoryExpertApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
          ${(form as any).laboratoryManagerApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید مدیر آزمایشگاه</div>
              <div class="signature-content">${(form as any).laboratoryManagerApproval}</div>
              ${(form as any).laboratoryManagerApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).laboratoryManagerApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
        </div>
      </div>
    </div>
    
    <!-- بخش انبار -->
    <div class="section">
      <div class="section-header">📦 بخش انبار</div>
      <div class="section-content">
        <div class="field-row">
          <div class="field">
            <div class="field-label">تاریخ تحویل نمونه‌ها</div>
            <div class="field-value">${(form as any).warehouseDeliveryDate || '-'}</div>
          </div>
        </div>
        
        <h4>اقلام سالم</h4>
        <div class="field-row">
          <div class="field">
            <div class="field-label">تعداد سالم</div>
            <div class="field-value">${(form as any).warehouseHealthyCount || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">واحد</div>
            <div class="field-value">${(form as any).warehouseHealthyUnit || '-'}</div>
          </div>
        </div>
        
        <h4>ضایعات</h4>
        <div class="field-row">
          <div class="field">
            <div class="field-label">تعداد ضایعات</div>
            <div class="field-value">${(form as any).warehouseWasteCount || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">واحد</div>
            <div class="field-value">${(form as any).warehouseWasteUnit || '-'}</div>
          </div>
        </div>
        
        <h4>تاییدات انبار</h4>
        <div class="signature-section">
          ${(form as any).warehouseExpertApproval ? `
            <div class="signature-box">
              <div class="signature-title">تایید کارشناس/سرپرست انبار</div>
              <div class="signature-content">${(form as any).warehouseExpertApproval}</div>
              ${(form as any).warehouseExpertApprovalImageUrl ? `<div class="signature-image"><img src="${(form as any).warehouseExpertApprovalImageUrl}" alt="امضای دیجیتال" /></div>` : ''}
            </div>
          ` : ''}
        </div>
      </div>
    </div>
  `;
}

function generatePartsTable(partsTableData: string | any): string {
  console.log('generatePartsTable called with:', partsTableData);
  
  let parts;
  
  // Handle if partsTableData is already an array
  if (Array.isArray(partsTableData)) {
    parts = partsTableData;
  } else if (typeof partsTableData === 'string' && partsTableData.trim()) {
    try {
      parts = JSON.parse(partsTableData);
    } catch (e) {
      console.log('Error parsing partsTableData:', e);
      return '';
    }
  } else {
    return '';
  }
  
  if (!Array.isArray(parts) || parts.length === 0) return '';
  
  // Filter out empty parts
  const validParts = parts.filter(part => 
    part && (part.partName || part.name) && (part.partName || part.name).trim()
  );
  
  if (validParts.length === 0) return '';
  
  console.log('Valid parts found:', validParts);
  
  return `
    <div style="margin: 20px 0;">
      <h4>جدول قطعات</h4>
      <table>
        <thead>
          <tr>
            <th>نام قطعه</th>
            <th>مقدار درخواستی</th>
            <th>واحد</th>
          </tr>
        </thead>
        <tbody>
          ${validParts.map((part: any) => `
            <tr>
              <td>${part.partName || part.name || '-'}</td>
              <td>${part.requestedAmount || part.quantity || '-'}</td>
              <td>${part.unit || '-'}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
  `;
}

function generateMonitoringTable(monitoringData: string): string {
  if (!monitoringData) return '';
  
  try {
    const monitoring = JSON.parse(monitoringData);
    if (!Array.isArray(monitoring) || monitoring.length === 0) return '';
    
    return `
      <div style="margin: 20px 0;">
        <h4>جدول پایش</h4>
        <table>
          <thead>
            <tr>
              <th>موارد پایش</th>
            </tr>
          </thead>
          <tbody>
            ${monitoring.map((item: any) => `
              <tr>
                <td>${item.monitoringEntry || item.item || '-'}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
  } catch (e) {
    return '';
  }
}

function generateReceivedAmountsTable(receivedData: string): string {
  if (!receivedData) return '';
  
  try {
    const amounts = JSON.parse(receivedData);
    if (!Array.isArray(amounts) || amounts.length === 0) return '';
    
    return `
      <div style="margin: 20px 0;">
        <h4>مقدار دریافتی</h4>
        <table>
          <thead>
            <tr>
              <th>مقدار دریافتی</th>
              <th>واحد</th>
            </tr>
          </thead>
          <tbody>
            ${amounts.map((amount: any) => `
              <tr>
                <td>${amount.receivedAmount || '-'}</td>
                <td>${amount.unit || '-'}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
  } catch (e) {
    return '';
  }
}

function generateQualityPartsTable(partsData: string): string {
  if (!partsData) return '';
  
  try {
    const parts = JSON.parse(partsData);
    if (!Array.isArray(parts) || parts.length === 0) return '';
    
    return `
      <div style="margin: 20px 0;">
        <h4>جدول قطعات</h4>
        <table>
          <thead>
            <tr>
              <th>کد قطعه</th>
              <th>واحد</th>
              <th>نوع کالای مصرفی</th>
            </tr>
          </thead>
          <tbody>
            ${parts.map((part: any) => `
              <tr>
                <td>${part.partCode || '-'}</td>
                <td>${part.unit || '-'}</td>
                <td>${part.materialType || '-'}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
  } catch (e) {
    return '';
  }
}

function generateCodeRegistrationTable(codeData: string): string {
  if (!codeData) return '';
  
  try {
    const codes = JSON.parse(codeData);
    if (!Array.isArray(codes) || codes.length === 0) return '';
    
    return `
      <div style="margin: 20px 0;">
        <h4>جدول ثبت کد</h4>
        <table>
          <thead>
            <tr>
              <th>ثبت کد</th>
            </tr>
          </thead>
          <tbody>
            ${codes.map((code: any) => `
              <tr>
                <td>${code.code || '-'}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
  } catch (e) {
    return '';
  }
}

function generateTestsTable(testsData: string): string {
  if (!testsData) return '';
  
  try {
    const tests = JSON.parse(testsData);
    if (!Array.isArray(tests) || tests.length === 0) return '';
    
    return `
      <div style="margin: 20px 0;">
        <h4>جدول آزمون‌ها</h4>
        <table>
          <thead>
            <tr>
              <th>نام آزمون</th>
              <th>روش آزمون</th>
              <th>نتیجه آزمون</th>
            </tr>
          </thead>
          <tbody>
            ${tests.map((test: any) => `
              <tr>
                <td>${test.testName || '-'}</td>
                <td>${test.testMethod || '-'}</td>
                <td>${test.testResult || '-'}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
  } catch (e) {
    return '';
  }
}

function generatePartsStatusTable(partsStatusData: string | any): string {
  console.log('generatePartsStatusTable called with:', partsStatusData);
  
  let partsStatus;
  
  // Handle if partsStatusData is already an array
  if (Array.isArray(partsStatusData)) {
    partsStatus = partsStatusData;
  } else if (typeof partsStatusData === 'string' && partsStatusData.trim()) {
    try {
      partsStatus = JSON.parse(partsStatusData);
    } catch (e) {
      console.log('Error parsing partsStatusData:', e);
      return '';
    }
  } else {
    return '';
  }
  
  if (!Array.isArray(partsStatus) || partsStatus.length === 0) return '';
  
  // Filter out empty parts status
  const validPartsStatus = partsStatus.filter(part => 
    part && part.partName && part.partName.trim()
  );
  
  if (validPartsStatus.length === 0) return '';
  
  console.log('Valid parts status found:', validPartsStatus);
  
  return `
    <div style="margin: 20px 0;">
      <h4>جدول وضعیت قطعات</h4>
      <table>
        <thead>
          <tr>
            <th>نام قطعه</th>
            <th>وضعیت نهایی</th>
          </tr>
        </thead>
        <tbody>
          ${validPartsStatus.map((part: any) => `
            <tr>
              <td>${part.partName || '-'}</td>
              <td>${part.finalStatus || '-'}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
  `;
}