import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Link } from "wouter";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Archive, Search, Eye, Printer, ArrowRight } from "lucide-react";
import WorkflowHistory from "@/components/WorkflowHistory";

interface ArchivedForm {
  id: string;
  formNumber: string;
  indicatorNumber: string;
  productName: string;
  createdBy: string;
  creatorName: string;
  createdAt: string;
  archivedAt: string;
}

export default function ArchivedForms() {
  const [searchTerm, setSearchTerm] = useState("");

  const { data: archivedForms, isLoading } = useQuery({
    queryKey: ['/api/forms/archived'],
  });

  const filteredForms = (archivedForms as ArchivedForm[] || [])?.filter((form: ArchivedForm) =>
    form.indicatorNumber?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    form.formNumber?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    form.productName?.toLowerCase().includes(searchTerm.toLowerCase())
  ) || [];

  const handlePrint = async (formId: string, event: any) => {
    try {
      // Show loading state
      const originalText = event?.target?.textContent;
      if (event?.target) {
        event.target.textContent = 'در حال تولید...';
        event.target.disabled = true;
      }

      console.log('Fetching form data for ID:', formId);
      
      // Fetch form data and create print view
      const response = await fetch(`/api/forms/${formId}`);
      
      if (response.ok) {
        const form = await response.json();
        console.log('Form data received:', form);
        
        // Create printable HTML content
        console.log('Generating print HTML...');
        const printContent = generatePrintHTML(form);
        console.log('Print HTML generated successfully');
        
        // Open in new window
        const newWindow = window.open('', '_blank', 'width=1200,height=800,scrollbars=yes,resizable=yes');
        if (newWindow) {
          newWindow.document.write(printContent);
          newWindow.document.close();
          console.log('Print window opened successfully');
        } else {
          console.error('Failed to open new window - popup blocker might be active');
          alert('نمی‌توان پنجره جدید برای چاپ باز کرد. لطفاً popup blocker را غیرفعال کنید.');
        }
      } else {
        console.error('API response error:', response.status, response.statusText);
        alert('خطا در دریافت اطلاعات فرم: ' + response.status);
      }
      
    } catch (error: any) {
      console.error('خطا در نمایش فرم:', error);
      alert('خطا در نمایش فرم: ' + (error.message || error.toString()));
    } finally {
      // Reset button state
      setTimeout(() => {
        if (event?.target) {
          event.target.textContent = 'نمایش چاپی';
          event.target.disabled = false;
        }
      }, 1000);
    }
  };

  const generatePrintHTML = (form: any) => {
    const persianDate = form.createdAt ? new Intl.DateTimeFormat('fa-IR').format(new Date(form.createdAt)) : '-';
    
    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.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: 10px;
            line-height: 1.3;
            color: #333;
            direction: rtl;
            text-align: right;
            padding: 10px;
          }
          
          .header {
            text-align: center;
            border-bottom: 1px solid #2563eb;
            padding-bottom: 8px;
            margin-bottom: 12px;
          }
          
          .header h1 {
            font-size: 14px;
            font-weight: 700;
            color: #1e40af;
            margin-bottom: 4px;
          }
          
          .form-info {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 6px;
            margin-bottom: 12px;
            padding: 8px;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            background-color: #f9fafb;
          }
          
          .info-item {
            display: flex;
            align-items: center;
            gap: 4px;
          }
          
          .info-label {
            font-weight: 600;
            color: #374151;
            min-width: 60px;
            font-size: 9px;
          }
          
          .info-value {
            color: #1f2937;
            font-weight: 500;
            font-size: 9px;
          }
          
          .print-header {
            display: block;
            padding: 20px;
            margin-bottom: 20px;
            text-align: center;
            border-bottom: 1px solid #e5e7eb;
          }
          
          @media print {
            .print-header {
              display: none;
            }
            body { 
              -webkit-print-color-adjust: exact; 
              print-color-adjust: exact;
            }
          }
          
          .section {
            margin: 8px 0;
            padding: 8px;
            border: 1px solid #d1d5db;
            border-radius: 4px;
            background-color: #f9fafb;
            page-break-inside: avoid;
          }
          
          .section-title {
            font-size: 11px;
            font-weight: 700;
            color: #1e40af;
            margin-bottom: 6px;
            border-bottom: 1px solid #3b82f6;
            padding-bottom: 3px;
          }
          
          .field-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 6px;
            margin-bottom: 8px;
          }
          
          .field {
            display: flex;
            flex-direction: column;
            gap: 2px;
          }
          
          .field-label {
            font-weight: 600;
            color: #374151;
            font-size: 10px;
          }
          
          .field-value {
            color: #1f2937;
            padding: 3px 6px;
            border: 1px solid #d1d5db;
            border-radius: 2px;
            background-color: white;
            min-height: 18px;
            font-size: 10px;
          }
          
          .table-container {
            margin: 8px 0;
            overflow-x: auto;
          }
          
          .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 4px 0;
            background-color: white;
          }
          
          .data-table th, .data-table td {
            border: 1px solid #d1d5db;
            padding: 3px 6px;
            text-align: right;
            font-size: 12px;
          }
          
          .data-table th {
            background-color: #f3f4f6;
            font-weight: 600;
            color: #374151;
          }
          
          h4 {
            font-size: 11px;
            margin-bottom: 4px;
            font-weight: 600;
            color: #374151;
          }
          
          .departments-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            margin: 8px 0;
          }
          
          .department-row {
            display: contents;
          }
          
          .department-full-width {
            grid-column: 1 / -1;
          }

          .single-section {
            grid-column: 1 / -1;
          }
          
          .signature-section {
            margin-top: 8px;
            padding: 6px;
            border: 1px solid #3b82f6;
            border-radius: 4px;
            background-color: #eff6ff;
          }
          
          .signature-row {
            display: flex;
            flex-direction: row;
            gap: 4px;
            margin-top: 4px;
            justify-content: space-between;
          }
          
          .signature-box {
            padding: 3px;
            border: 1px solid #9ca3af;
            border-radius: 2px;
            background-color: white;
            text-align: center;
            min-height: 30px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            flex: 1;
            min-width: 0;
          }
          
          .signature-title {
            font-weight: 600;
            color: #374151;
            margin-bottom: 3px;
            font-size: 8px;
          }
          
          .signature-image {
            max-width: 50px;
            max-height: 25px;
            margin: 1px 0;
          }
          
          .signature-date {
            font-size: 7px;
            color: #6b7280;
            margin-top: 2px;
          }
        </style>
      </head>
      <body>
        <div class="print-header">
          <button onclick="window.print()" style="background: #3b82f6; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; font-family: 'Vazir', Arial, sans-serif; font-size: 14px; margin: 0 10px;">🖨️ چاپ فرم</button>
          <button onclick="window.close()" style="background: #6b7280; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; margin: 0 10px; font-family: 'Vazir', Arial, sans-serif; font-size: 14px;">❌ بستن</button>
        </div>
        
        <div class="header">
          <h1>فرم تامین نمونه کالا</h1>
          <h2 style="font-size: 12px; color: #6b7280; margin-top: 8px;">شماره اندیکاتور: ${form.indicatorNumber || form.formNumber}</h2>
        </div>
        
        
        ${generateDepartmentSectionsGrid(form)}
        
        <div style="margin-top: 15px; padding-top: 8px; border-top: 1px solid #e5e7eb; text-align: center; color: #6b7280; font-size: 7px;">
          <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>
    `;
  };

  const generateDepartmentSectionsGrid = (form: any) => {
    // بررسی اینکه آیا هر بخش داده دارد یا نه
    const hasEngineeringData = checkEngineeringData(form);
    const hasPlanningData = checkPlanningData(form);
    const hasCommercialData = checkCommercialData(form);
    const hasQualityData = checkQualityData(form);
    const hasFinancialData = checkFinancialData(form);
    const hasLaboratoryData = checkLaboratoryData(form);
    const hasWarehouseData = checkWarehouseData(form);

    let sectionsHtml = '<div class="departments-grid">';
    
    // ردیف اول: مهندسی و برنامه‌ریزی
    if (hasEngineeringData || hasPlanningData) {
      sectionsHtml += '<div class="department-row">';
      if (hasEngineeringData) sectionsHtml += generateEngineeringSection(form);
      if (hasPlanningData) sectionsHtml += generatePlanningSection(form);
      sectionsHtml += '</div>';
    }
    
    // ردیف دوم: بازرگانی و کیفیت
    if (hasCommercialData || hasQualityData) {
      sectionsHtml += '<div class="department-row">';
      if (hasCommercialData) sectionsHtml += generateCommercialSection(form);
      if (hasQualityData) sectionsHtml += generateQualitySection(form);
      sectionsHtml += '</div>';
    }
    
    // ردیف سوم: مالی و آزمایشگاه
    if (hasFinancialData || hasLaboratoryData) {
      sectionsHtml += '<div class="department-row">';
      if (hasFinancialData) sectionsHtml += generateFinancialSection(form);
      if (hasLaboratoryData) sectionsHtml += generateLaboratorySection(form);
      sectionsHtml += '</div>';
    }
    
    // ردیف چهارم: انبار (تمام عرض)
    if (hasWarehouseData) {
      sectionsHtml += '<div class="department-full-width">' + generateWarehouseSection(form) + '</div>';
    }
    
    sectionsHtml += '</div>';
    return sectionsHtml;
  };

  // توابع بررسی داده برای هر بخش
  const checkEngineeringData = (form: any) => {
    return form.productName || form.indicatorNumber || form.suggestedSupplier || 
           form.drawingCode || form.sentDocuments || form.documentSendDate || 
           form.needDate || form.actionNumber || form.engineeringDate || 
           form.issueReason || form.supplyOrder || form.expertApproval || 
           form.managerApproval || (form.partsTable && form.partsTable.length > 0);
  };

  const checkPlanningData = (form: any) => {
    return form.planningExecutionDate || form.planningManagerApproval || 
           (form.planningMonitoringTable && form.planningMonitoringTable.length > 0);
  };

  const checkCommercialData = (form: any) => {
    return form.commercialSupplierNameCode || form.commercialSampleSendDate || 
           form.commercialBillNumber || form.commercialShipmentCode || 
           form.commercialContractorCertificate || form.commercialExpertApproval || 
           form.commercialManagerApproval || (form.commercialReceivedTable && form.commercialReceivedTable.length > 0);
  };

  const checkQualityData = (form: any) => {
    return form.qualityExecutionDate || form.qualityManagerApproval || 
           (form.qualityPartsTable && form.qualityPartsTable.length > 0);
  };

  const checkFinancialData = (form: any) => {
    return form.financialExecutionDate || form.financialExpertApproval || 
           (form.financialCodeTable && form.financialCodeTable.length > 0);
  };

  const checkLaboratoryData = (form: any) => {
    return form.laboratorySpecialStorageConditions || form.laboratoryExecutionDate || 
           form.laboratoryFinalStatus || form.laboratoryTestRequestNumber || 
           form.laboratoryTestRequestDate || form.dimensionalPartName || 
           form.dimensionalLotCode || form.dimensionalSupplier || 
           form.laboratoryExpertApproval || form.laboratoryManagerApproval ||
           (form.laboratoryTestsTable && form.laboratoryTestsTable.length > 0) ||
           (form.laboratoryPartsStatusTable && form.laboratoryPartsStatusTable.length > 0) ||
           (form.dimensionalMeasurementsTable && form.dimensionalMeasurementsTable.length > 0);
  };

  const checkWarehouseData = (form: any) => {
    return form.warehouseDeliveryDate || form.warehouseHealthyCount || 
           form.warehouseHealthyUnit || form.warehouseWasteCount || 
           form.warehouseWasteUnit || form.warehouseExpertApproval;
  };

  const generateEngineeringSection = (form: any) => {
    let parts = [];
    try {
      if (typeof form.partsTable === 'string') {
        parts = JSON.parse(form.partsTable);
      } else if (Array.isArray(form.partsTable)) {
        parts = form.partsTable;
      } else {
        parts = [];
      }
    } catch (e) {
      console.log('Error parsing partsTable:', e);
      parts = [];
    }
    
    return `
      <div class="section">
        <div class="section-title">🔧 بخش مهندسی</div>
        
        <div class="field-grid">
          <div class="field">
            <div class="field-label">نام محصول</div>
            <div class="field-value">${form.productName || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره اندیکاتور</div>
            <div class="field-value">${form.indicatorNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره اندیکاتور فرم قبلی</div>
            <div class="field-value">${form.previousFormIndicator || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">کد نقشه</div>
            <div class="field-value">${form.drawingCode || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">فاز تکوین محصول جدید</div>
            <div class="field-value">${form.newProductDevPhase || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">کد مرکز هزینه پروژه</div>
            <div class="field-value">${form.projectCostCenterCode || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تامین کننده پیشنهادی</div>
            <div class="field-value">${form.suggestedSupplier || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">مجری تامین</div>
            <div class="field-value">${form.supplyExecutive || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">مدارک ارسالی</div>
            <div class="field-value">${form.sentDocuments || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ ارسال مدارک</div>
            <div class="field-value">${form.documentSendDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ نیاز</div>
            <div class="field-value">${form.needDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره اقدام</div>
            <div class="field-value">${form.actionNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ</div>
            <div class="field-value">${form.engineeringDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">علت صدور</div>
            <div class="field-value">${form.issueReason || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">مرتبه تامین</div>
            <div class="field-value">${form.supplyOrder || '-'}</div>
          </div>
        </div>
        
        ${parts.length > 0 ? `
        <div class="table-container">
          <h4>جدول قطعات</h4>
          <table class="data-table">
            <thead>
              <tr>
                <th>نام قطعه</th>
                <th>مقدار درخواستی</th>
                <th>واحد</th>
              </tr>
            </thead>
            <tbody>
              ${parts.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>
        ` : '<div class="table-container"><h4>جدول قطعات</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ قطعه‌ای ثبت نشده است</p></div>'}
        
        ${generateSignatureSection('engineering', form)}
      </div>
    `;
  };

  const generatePlanningSection = (form: any) => {
    let monitoring = [];
    try {
      if (typeof form.planningMonitoringTable === 'string') {
        monitoring = JSON.parse(form.planningMonitoringTable);
      } else if (Array.isArray(form.planningMonitoringTable)) {
        monitoring = form.planningMonitoringTable;
      } else {
        monitoring = [];
      }
    } catch (e) {
      console.log('Error parsing planningMonitoringTable:', e);
      monitoring = [];
    }
    
    return `
      <div class="section">
        <div class="section-title">📋 بخش برنامه‌ریزی</div>
        
        <div class="field-grid">
          <div class="field">
            <div class="field-label">تاریخ اجرا</div>
            <div class="field-value">${form.planningExecutionDate || form.planExecutionDate || '-'}</div>
          </div>
        </div>
        
        ${monitoring.length > 0 ? `
        <div class="table-container">
          <h4>جدول پایش</h4>
          <table class="data-table">
            <thead>
              <tr>
                <th>موارد پایش</th>
              </tr>
            </thead>
            <tbody>
              ${monitoring.map((item: any) => `
                <tr>
                  <td>${item.monitoringEntry || item.item || '-'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        ` : '<div class="table-container"><h4>جدول پایش</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ موردی برای پایش ثبت نشده است</p></div>'}
        
        ${generateSignatureSection('planning', form)}
      </div>
    `;
  };

  const generateCommercialSection = (form: any) => {
    let receivedAmounts = [];
    try {
      if (typeof form.commercialReceivedTable === 'string') {
        receivedAmounts = JSON.parse(form.commercialReceivedTable);
      } else if (Array.isArray(form.commercialReceivedTable)) {
        receivedAmounts = form.commercialReceivedTable;
      } else {
        receivedAmounts = [];
      }
    } catch (e) {
      console.log('Error parsing commercialReceivedTable:', e);
      receivedAmounts = [];
    }
    
    return `
      <div class="section">
        <div class="section-title">💼 بخش بازرگانی</div>
        
        <div class="field-grid">
          <div class="field">
            <div class="field-label">نام/کد تامین کننده</div>
            <div class="field-value">${form.commercialSupplierNameCode || form.commSupplierInfo || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ ارسال نمونه</div>
            <div class="field-value">${form.commercialSampleSendDate || form.commSampleSendDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره بارنامه</div>
            <div class="field-value">${form.commercialBillNumber || form.commBillNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">کد محموله</div>
            <div class="field-value">${form.commercialShipmentCode || form.commShipmentCode || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">گواهی پیمانکار</div>
            <div class="field-value">${form.commercialContractorCertificate || form.commContractorCertificate || '-'}</div>
          </div>
        </div>
        
        ${receivedAmounts.length > 0 ? `
        <div class="table-container">
          <h4>مقدار دریافتی</h4>
          <table class="data-table">
            <thead>
              <tr>
                <th>مقدار دریافتی</th>
                <th>واحد</th>
              </tr>
            </thead>
            <tbody>
              ${receivedAmounts.map((amount: any) => `
                <tr>
                  <td>${amount.receivedAmount || '-'}</td>
                  <td>${amount.unit || '-'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        ` : '<div class="table-container"><h4>مقدار دریافتی</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ مقداری ثبت نشده است</p></div>'}
        
        ${generateSignatureSection('commercial', form)}
      </div>
    `;
  };

  const generateQualitySection = (form: any) => {
    let parts = [];
    try {
      if (typeof form.qualityPartsTable === 'string') {
        parts = JSON.parse(form.qualityPartsTable);
      } else if (Array.isArray(form.qualityPartsTable)) {
        parts = form.qualityPartsTable;
      } else {
        parts = [];
      }
    } catch (e) {
      console.log('Error parsing qualityPartsTable:', e);
      parts = [];
    }
    
    return `
      <div class="section">
        <div class="section-title">✅ بخش کیفیت</div>
        
        <div class="field-grid">
          <div class="field">
            <div class="field-label">تاریخ اجرا</div>
            <div class="field-value">${form.qualityExecutionDate || form.qualExecutionDate || '-'}</div>
          </div>
        </div>
        
        ${parts.length > 0 ? `
        <div class="table-container">
          <h4>جدول قطعات</h4>
          <table class="data-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>
        ` : '<div class="table-container"><h4>جدول قطعات</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ قطعه‌ای ثبت نشده است</p></div>'}
        
        ${generateSignatureSection('quality', form)}
      </div>
    `;
  };

  const generateFinancialSection = (form: any) => {
    let codeRegistrations = [];
    try {
      if (typeof form.financialCodeTable === 'string') {
        codeRegistrations = JSON.parse(form.financialCodeTable);
      } else if (Array.isArray(form.financialCodeTable)) {
        codeRegistrations = form.financialCodeTable;
      } else {
        codeRegistrations = [];
      }
    } catch (e) {
      console.log('Error parsing financialCodeTable:', e);
      codeRegistrations = [];
    }
    
    return `
      <div class="section">
        <div class="section-title">💰 بخش مالی</div>
        
        <div class="field-grid">
          <div class="field">
            <div class="field-label">تاریخ اجرا</div>
            <div class="field-value">${form.financialExecutionDate || form.finExecutionDate || '-'}</div>
          </div>
        </div>
        
        ${codeRegistrations.length > 0 ? `
        <div class="table-container">
          <h4>جدول ثبت کد</h4>
          <table class="data-table">
            <thead>
              <tr>
                <th>ثبت کد</th>
              </tr>
            </thead>
            <tbody>
              ${codeRegistrations.map((code: any) => `
                <tr>
                  <td>${code.code || '-'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        ` : '<div class="table-container"><h4>جدول ثبت کد</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ کدی ثبت نشده است</p></div>'}
        
        ${generateSignatureSection('financial', form)}
      </div>
    `;
  };

  const generateLaboratorySection = (form: any) => {
    let tests = [];
    let partsStatus = [];
    let dimensionalMeasurements = [];
    
    try {
      // بررسی اینکه آیا فیلد string است یا آرایه
      if (typeof form.laboratoryTestsTable === 'string') {
        tests = JSON.parse(form.laboratoryTestsTable);
      } else if (Array.isArray(form.laboratoryTestsTable)) {
        tests = form.laboratoryTestsTable;
      } else {
        tests = [];
      }
    } catch (e) {
      console.log('Error parsing laboratoryTestsTable:', e);
      tests = [];
    }

    try {
      if (typeof form.laboratoryPartsStatusTable === 'string') {
        partsStatus = JSON.parse(form.laboratoryPartsStatusTable);
      } else if (Array.isArray(form.laboratoryPartsStatusTable)) {
        partsStatus = form.laboratoryPartsStatusTable;
      } else {
        partsStatus = [];
      }
    } catch (e) {
      console.log('Error parsing laboratoryPartsStatusTable:', e);
      partsStatus = [];
    }

    try {
      if (typeof form.dimensionalMeasurementsTable === 'string') {
        dimensionalMeasurements = JSON.parse(form.dimensionalMeasurementsTable);
      } else if (Array.isArray(form.dimensionalMeasurementsTable)) {
        dimensionalMeasurements = form.dimensionalMeasurementsTable;
      } else {
        dimensionalMeasurements = [];
      }
    } catch (e) {
      console.log('Error parsing dimensionalMeasurementsTable:', e);
      dimensionalMeasurements = [];
    }
    
    return `
      <div class="section">
        <div class="section-title">🔬 بخش آزمایشگاه</div>
        
        <div class="field-grid">
          <div class="field">
            <div class="field-label">شرایط نگهداری خاص</div>
            <div class="field-value">${form.laboratorySpecialStorageConditions || form.labStorageConditions || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ اجرا</div>
            <div class="field-value">${form.laboratoryExecutionDate || form.labExecutionDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">وضعیت نهایی</div>
            <div class="field-value">${form.laboratoryFinalStatus || form.labFinalStatus || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره درخواست آزمون</div>
            <div class="field-value">${form.laboratoryTestRequestNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تاریخ درخواست آزمون</div>
            <div class="field-value">${form.laboratoryTestRequestDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">نام قطعه</div>
            <div class="field-value">${form.dimensionalPartName || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">کد محموله</div>
            <div class="field-value">${form.dimensionalLotCode || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره نقشه/طرح تست</div>
            <div class="field-value">${form.dimensionalDrawingTestNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">تامین کننده</div>
            <div class="field-value">${form.dimensionalSupplier || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شماره تامین نمونه</div>
            <div class="field-value">${form.dimensionalSampleSupplyNumber || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">شرایط خاص نگهداری</div>
            <div class="field-value">${form.dimensionalSpecialStorageConditions || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">وضعیت محموله</div>
            <div class="field-value">${form.dimensionalLotStatus || '-'}</div>
          </div>
        </div>
        
        ${tests.length > 0 ? `
        <div class="table-container">
          <h4>جدول آزمون‌ها</h4>
          <table class="data-table">
            <thead>
              <tr>
                <th>نام آزمون</th>
                <th>روش آزمون</th>
                <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>
                  <td>${test.partStatus || '-'}</td>
                  <td>${test.comments || '-'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        ` : '<div class="table-container"><h4>جدول آزمون‌ها</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ آزمونی ثبت نشده است</p></div>'}

        ${partsStatus.length > 0 ? `
        <div class="table-container">
          <h4>وضعیت نهایی قطعات</h4>
          <table class="data-table">
            <thead>
              <tr>
                <th>نام قطعه</th>
                <th>وضعیت نهایی</th>
              </tr>
            </thead>
            <tbody>
              ${partsStatus.map((part: any) => `
                <tr>
                  <td>${part.partName || '-'}</td>
                  <td>${part.finalStatus || '-'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        ` : '<div class="table-container"><h4>وضعیت نهایی قطعات</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ قطعه‌ای ثبت نشده است</p></div>'}

        ${dimensionalMeasurements.length > 0 ? `
        <div class="table-container">
          <h4>ثبت مقادیر اندازه‌گیری ابعادی</h4>
          <table class="data-table">
            <thead>
              <tr>
                <th>پارامتر کنترلی</th>
                <th>حدود پذیرش</th>
                <th>شماره نمونه</th>
                <th>توضیحات</th>
              </tr>
            </thead>
            <tbody>
              ${dimensionalMeasurements.map((measurement: any) => `
                <tr>
                  <td>${measurement.controlParameter || '-'}</td>
                  <td>${measurement.acceptanceRange || '-'}</td>
                  <td>${measurement.sampleNumber || '-'}</td>
                  <td>${measurement.comments || '-'}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
        ` : '<div class="table-container"><h4>ثبت مقادیر اندازه‌گیری ابعادی</h4><p style="color: #6b7280; text-align: center; padding: 20px;">هیچ اندازه‌گیری ثبت نشده است</p></div>'}
        
        ${generateSignatureSection('laboratory', form)}
      </div>
    `;
  };

  const generateWarehouseSection = (form: any) => {
    return `
      <div class="section">
        <div class="section-title">📦 بخش انبار</div>
        
        <div class="field-grid">
          <div class="field">
            <div class="field-label">تاریخ تحویل</div>
            <div class="field-value">${form.warehouseDeliveryDate || form.wareDeliveryDate || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">مقدار سالم</div>
            <div class="field-value">${form.warehouseHealthyCount || form.wareHealthyQuantity || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">واحد سالم</div>
            <div class="field-value">${form.warehouseHealthyUnit || form.wareHealthyUnit || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">مقدار ضایعات</div>
            <div class="field-value">${form.warehouseWasteCount || form.wareWasteQuantity || '-'}</div>
          </div>
          <div class="field">
            <div class="field-label">واحد ضایعات</div>
            <div class="field-value">${form.warehouseWasteUnit || form.wareWasteUnit || '-'}</div>
          </div>
        </div>
        
        ${generateSignatureSection('warehouse', form)}
      </div>
    `;
  };

  const extractPositionAndDate = (signatureText: string) => {
    if (!signatureText) return '';
    
    const lines = signatureText.split('\n');
    let position = '';
    let date = '';
    
    for (const line of lines) {
      if (line.includes('سمت:')) {
        position = line.replace('سمت:', '').trim();
      }
      if (line.includes('تاریخ:')) {
        date = line.replace('تاریخ:', '').trim();
      }
    }
    
    return [position, date].filter(Boolean).join('\n');
  };

  const generateSignatureSection = (department: string, form: any) => {
    const getSignatureData = (dept: string, type: string) => {
      // نگاشت فیلدهای دیتابیس
      const fieldMappings = {
        engineering: {
          expert: { image: 'expertApprovalImageUrl', text: 'expertApproval' },
          manager: { image: 'managerApprovalImageUrl', text: 'managerApproval' }
        },
        planning: {
          expert: { image: 'planningExpertApprovalImageUrl', text: 'planningExpertApproval' },
          manager: { image: 'planningManagerApprovalImageUrl', text: 'planningManagerApproval' }
        },
        commercial: {
          expert: { image: 'commercialExpertApprovalImageUrl', text: 'commercialExpertApproval' },
          manager: { image: 'commercialManagerApprovalImageUrl', text: 'commercialManagerApproval' }
        },
        quality: {
          expert: { image: 'qualityExpertApprovalImageUrl', text: 'qualityExpertApproval' },
          manager: { image: 'qualityManagerApprovalImageUrl', text: 'qualityManagerApproval' }
        },
        financial: {
          expert: { image: 'financialExpertApprovalImageUrl', text: 'financialExpertApproval' },
          manager: { image: '', text: '' } // مالی فقط کارشناس دارد
        },
        laboratory: {
          expert: { image: 'laboratoryExpertApprovalImageUrl', text: 'laboratoryExpertApproval' },
          manager: { image: 'laboratoryManagerApprovalImageUrl', text: 'laboratoryManagerApproval' }
        },
        warehouse: {
          expert: { image: 'warehouseExpertApprovalImageUrl', text: 'warehouseExpertApproval' },
          manager: { image: '', text: '' } // انبار فقط کارشناس دارد
        }
      };
      
      const typeKey = type.toLowerCase();
      const deptMapping = fieldMappings[dept as keyof typeof fieldMappings];
      const mapping = deptMapping?.[typeKey as keyof typeof deptMapping];
      
      return {
        image: mapping?.image ? form[mapping.image] : null,
        text: mapping?.text ? form[mapping.text] : null
      };
    };

    const expertSig = getSignatureData(department, 'Expert');
    const managerSig = getSignatureData(department, 'Manager');
    
    const departmentTitles: { [key: string]: string } = {
      engineering: 'مهندسی',
      planning: 'برنامه‌ریزی', 
      commercial: 'بازرگانی',
      quality: 'کیفیت',
      financial: 'مالی',
      laboratory: 'آزمایشگاه',
      warehouse: 'انبار'
    };

    let signatureHTML = `
      <div class="signature-section">
        <div class="section-title">امضاهای ${departmentTitles[department] || department}</div>
        <div class="signature-row">
    `;

    // Expert signature
    if (expertSig.image || expertSig.text) {
      const expertTitle = department === 'planning' ? 'سرپرست/کارشناس' : 
                         (department === 'financial' || department === 'warehouse') ? 'کارشناس/سرپرست' : 'کارشناس';
      signatureHTML += `
        <div class="signature-box">
          <div class="signature-title">تایید ${expertTitle}</div>
          ${expertSig.image ? `<img src="${expertSig.image}" alt="امضا" class="signature-image" />` : ''}
          ${expertSig.text ? `<div class="signature-text" style="font-size: 7px; color: #374151; margin-top: 2px; line-height: 1.2;">${extractPositionAndDate(expertSig.text)}</div>` : ''}
          ${!expertSig.image && !expertSig.text ? '<div style="color: #9ca3af;">امضا ثبت نشده</div>' : ''}
        </div>
      `;
    }

    // Manager signature  
    if (managerSig.image || managerSig.text) {
      signatureHTML += `
        <div class="signature-box">
          <div class="signature-title">تایید مدیر</div>
          ${managerSig.image ? `<img src="${managerSig.image}" alt="امضا" class="signature-image" />` : ''}
          ${managerSig.text ? `<div class="signature-text" style="font-size: 7px; color: #374151; margin-top: 2px; line-height: 1.2;">${extractPositionAndDate(managerSig.text)}</div>` : ''}
          ${!managerSig.image && !managerSig.text ? '<div style="color: #9ca3af;">امضا ثبت نشده</div>' : ''}
        </div>
      `;
    }

    // Show both expert and manager sections (even if empty for some departments)
    const showManagerSignature = !['financial', 'warehouse'].includes(department);
    
    // If no expert signature
    if (!expertSig.image && !expertSig.text) {
      const expertTitle = department === 'planning' ? 'سرپرست/کارشناس' : 
                         (department === 'financial' || department === 'warehouse') ? 'کارشناس/سرپرست' : 'کارشناس';
      signatureHTML += `
        <div class="signature-box">
          <div class="signature-title">تایید ${expertTitle}</div>
          <div style="color: #9ca3af;">امضا ثبت نشده</div>
        </div>
      `;
    }
    
    // If should show manager signature and no manager signature
    if (showManagerSignature && !managerSig.image && !managerSig.text) {
      signatureHTML += `
        <div class="signature-box">
          <div class="signature-title">تایید مدیر</div>
          <div style="color: #9ca3af;">امضا ثبت نشده</div>
        </div>
      `;
    }

    signatureHTML += `
        </div>
      </div>
    `;

    return signatureHTML;
  };

  return (
    <div className="min-h-screen bg-gray-50 p-4" dir="rtl">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <Archive className="h-6 w-6 text-blue-600" />
            <h1 className="text-2xl font-bold text-gray-900">فرم‌های بسته شده (آرشیو)</h1>
          </div>
          <Link href="/">
            <Button variant="outline" className="flex items-center gap-2">
              <ArrowRight className="h-4 w-4" />
              بازگشت به داشبورد
            </Button>
          </Link>
        </div>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>لیست فرم‌های آرشیو شده</span>
              <Badge variant="secondary" className="text-sm">
                {filteredForms.length} فرم
              </Badge>
            </CardTitle>
            
            {/* Search */}
            <div className="flex items-center gap-2 max-w-md">
              <Search className="h-4 w-4 text-gray-400" />
              <Input
                placeholder="جستجو با شماره اندیکاتور، شماره فرم یا نام محصول..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="text-right"
              />
            </div>
          </CardHeader>
          
          <CardContent>
            {isLoading ? (
              <div className="text-center py-8">در حال بارگذاری...</div>
            ) : filteredForms.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                {searchTerm ? 'هیچ فرمی با این جستجو یافت نشد' : 'هیچ فرم آرشیو شده‌ای وجود ندارد'}
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-center">شماره اندیکاتور</TableHead>
                    <TableHead className="text-center">نام محصول</TableHead>
                    <TableHead className="text-center">ایجادکننده</TableHead>
                    <TableHead className="text-center">تاریخ ایجاد</TableHead>
                    <TableHead className="text-center">تاریخ آرشیو</TableHead>
                    <TableHead className="text-center">عملیات</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredForms.map((form: ArchivedForm) => (
                    <TableRow key={form.id}>
                      <TableCell className="text-center font-medium">
                        <Badge variant="outline" className="text-xs">
                          {form.indicatorNumber || '-'}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-center">
                        {form.productName || '-'}
                      </TableCell>
                      <TableCell className="text-center">
                        {form.creatorName}
                      </TableCell>
                      <TableCell className="text-center text-sm">
                        {new Date(form.createdAt).toLocaleDateString('fa-IR')}
                      </TableCell>
                      <TableCell className="text-center text-sm">
                        {form.archivedAt ? new Date(form.archivedAt).toLocaleDateString('fa-IR') : '-'}
                      </TableCell>
                      <TableCell className="text-center">
                        <div className="flex items-center justify-center gap-2">
                          <Link href={`/form/${form.id}`}>
                            <Button variant="outline" size="sm" className="flex items-center gap-1">
                              <Eye className="h-3 w-3" />
                              مشاهده
                            </Button>
                          </Link>
                          
                          <Button 
                            variant="outline" 
                            size="sm" 
                            onClick={(e) => handlePrint(form.id, e)}
                            className="flex items-center gap-1"
                          >
                            <Printer className="h-3 w-3" />
                            نمایش چاپی
                          </Button>
                          
                          <WorkflowHistory formId={form.id} />
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}