/**
 * 검사 성적서 문서 (발주서 스타일 기반)
 * 수입검사/중간검사/제품검사 성적서 출력
 */

import type { InspectionStandard } from "./contexts/DataContext";

interface InspectionStandardDocumentProps {
  standard: InspectionStandard;
  actualData?: {
    basicInfo: Record<string, string>;
    inspectionResults: Array<Record<string, any>>;
    notes?: string;
    judgment?: string;
    inspectorName?: string;
    inspectionDate?: string;
  };
}

export function InspectionStandardDocument({ standard, actualData }: InspectionStandardDocumentProps) {
  const { documentTemplate } = standard;

  // 실제 데이터 또는 템플릿 데이터 사용
  const basicInfo = actualData?.basicInfo || {};
  const inspectionResults = actualData?.inspectionResults || documentTemplate.inspectionItems;
  const notes = actualData?.notes || '';
  const judgment = actualData?.judgment || '';

  const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getFullYear()}년 ${String(date.getMonth() + 1).padStart(2, '0')}월 ${String(date.getDate()).padStart(2, '0')}일`;
  };

  return (
    <>
      <style>{`
        @media print {
          @page {
            size: A4 portrait;
            margin: 10mm;
          }
          
          body {
            background: white !important;
          }
          
          #inspection-document-content {
            background: white !important;
            padding: 0 !important;
          }
        }
        
        /* 검사 성적서 공문서 스타일 (발주서 기반) */
        .inspection-doc {
          font-family: 'Malgun Gothic', 'Apple SD Gothic Neo', sans-serif;
          background: white;
          color: #000;
          line-height: 1.4;
        }
        
        .insp-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 20px;
          padding-bottom: 15px;
          border-bottom: 2px solid #000;
        }
        
        .insp-title {
          flex: 1;
          text-align: center;
        }
        
        .insp-title h1 {
          font-size: 36px;
          font-weight: 700;
          letter-spacing: 8px;
          margin: 0;
        }
        
        .insp-approval-section {
          border: 2px solid #000;
          background: white;
        }
        
        .insp-number-row {
          display: grid;
          grid-template-columns: 100px 1fr;
          border-bottom: 2px solid #000;
        }
        
        .insp-number-label {
          background: #e8e8e8;
          border-right: 2px solid #000;
          padding: 8px;
          text-align: center;
          font-weight: 700;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        .insp-number-value {
          background: white;
          padding: 8px;
          text-align: center;
          font-weight: 700;
          font-size: 14px;
          color: #000;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        .insp-approval-box {
          width: 100%;
          border: none;
          display: grid;
          grid-template-columns: 60px 1fr;
        }
        
        .insp-approval-merged-vertical-cell {
          background: #e8e8e8;
          border-right: 2px solid #000;
          writing-mode: vertical-rl;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
          font-size: 16px;
          letter-spacing: 8px;
          padding: 10px 0;
        }
        
        .insp-approval-header {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
          border-bottom: 1px solid #000;
        }
        
        .insp-approval-header-cell {
          background: #e8e8e8;
          border-right: 1px solid #000;
          padding: 8px;
          text-align: center;
          font-weight: 700;
          font-size: 12px;
        }
        
        .insp-approval-header-cell:last-child {
          border-right: none;
        }
        
        .insp-approval-content-row {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
          border-bottom: 1px solid #000;
        }
        
        .insp-approval-signature-cell {
          background: white;
          border-right: 1px solid #000;
          padding: 20px 8px;
          text-align: center;
          min-height: 60px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 700;
        }
        
        .insp-approval-signature-cell:last-child {
          border-right: none;
        }
        
        .insp-approval-name-row {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
        }
        
        .insp-approval-name-cell {
          background: #f5f5f5;
          border-right: 1px solid #000;
          padding: 8px;
          text-align: center;
          font-size: 12px;
        }
        
        .insp-approval-name-cell:last-child {
          border-right: none;
        }
        
        .insp-section-table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 15px;
          border: 2px solid #000;
        }
        
        .insp-section-header {
          background: #e8e8e8;
          border: 1px solid #000;
          padding: 10px;
          text-align: center;
          font-weight: 700;
          font-size: 13px;
        }
        
        .insp-section-content {
          background: white;
          border: 1px solid #000;
          padding: 10px;
          font-size: 13px;
        }
        
        .insp-items-table {
          width: 100%;
          border-collapse: collapse;
          border: 2px solid #000;
          margin-bottom: 20px;
        }
        
        .insp-items-table th {
          background: #e8e8e8;
          border: 1px solid #000;
          padding: 10px 5px;
          text-align: center;
          font-weight: 700;
          font-size: 12px;
        }
        
        .insp-items-table td {
          background: white;
          border: 1px solid #000;
          padding: 8px 5px;
          text-align: center;
          font-size: 12px;
        }
        
        .insp-footer-section {
          margin-top: 30px;
        }
        
        .insp-notes-box {
          border: 2px solid #000;
          padding: 15px;
          min-height: 80px;
          margin-bottom: 15px;
        }
        
        .insp-judgment-box {
          border: 2px solid #000;
          padding: 20px;
          text-align: center;
        }
        
        .insp-judgment-label {
          font-size: 18px;
          font-weight: 700;
          margin-bottom: 10px;
        }
        
        .insp-judgment-value {
          font-size: 24px;
          font-weight: 700;
          color: #0066cc;
        }
      `}</style>
      
      {/* 검사 성적서 내용 */}
      <div id="inspection-document-content" className="inspection-doc p-12 print:p-8">

        {/* 헤더: 제목 + 결재란 */}
        <div className="insp-header">
          {/* 제목 */}
          <div className="insp-title">
            <h1>{documentTemplate.title}</h1>
          </div>

          {/* 기준번호 + 결재란 */}
          <div className="insp-approval-section">
            {/* 기준번호 */}
            <div className="insp-number-row">
              <div className="insp-number-label">
                기준번호
              </div>
              <div className="insp-number-value">
                {standard.standardNumber}
              </div>
            </div>
            
            {/* 결재란 */}
            <div className="insp-approval-box">
              <div className="insp-approval-merged-vertical-cell">결<br/>재</div>
              {/* 결재란 헤더 */}
              <div className="insp-approval-header">
                {documentTemplate.approvalLines.map((line) => (
                  <div key={line.id} className="insp-approval-header-cell">{line.position}</div>
                ))}
              </div>
              {/* 결재+서명란 */}
              <div className="insp-approval-content-row">
                {documentTemplate.approvalLines.map((line) => (
                  <div key={line.id} className="insp-approval-signature-cell">
                    {line.name}
                  </div>
                ))}
              </div>
              {/* 이름/부서란 */}
              <div className="insp-approval-name-row">
                {documentTemplate.approvalLines.map((line) => (
                  <div key={line.id} className="insp-approval-name-cell">
                    {line.department || '-'}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* 기본 정보 */}
        <table className="insp-section-table">
          <tbody>
            {documentTemplate.basicInfoFields.map((field, index) => {
              // 2개씩 한 행에 표시
              if (index % 2 === 0) {
                const nextField = documentTemplate.basicInfoFields[index + 1];
                return (
                  <tr key={field.id}>
                    <th className="insp-section-header" style={{ width: '120px' }}>
                      {field.label}{field.required && <span className="text-red-500">*</span>}
                    </th>
                    <td className="insp-section-content" style={{ width: '35%' }}>
                      {basicInfo[field.id] || field.value || '-'}
                    </td>
                    {nextField ? (
                      <>
                        <th className="insp-section-header" style={{ width: '120px' }}>
                          {nextField.label}{nextField.required && <span className="text-red-500">*</span>}
                        </th>
                        <td className="insp-section-content" style={{ width: '35%' }}>
                          {basicInfo[nextField.id] || nextField.value || '-'}
                        </td>
                      </>
                    ) : (
                      <td className="insp-section-content" colSpan={2}></td>
                    )}
                  </tr>
                );
              }
              return null;
            })}
          </tbody>
        </table>

        {/* 검사 항목 */}
        <table className="insp-items-table">
          <thead>
            <tr>
              {documentTemplate.inspectionColumns.map((col) => (
                <th key={col.id} style={{ width: col.width }}>
                  {col.name}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {inspectionResults.map((item) => (
              <tr key={item.id}>
                {documentTemplate.inspectionColumns.map((col) => (
                  <td key={col.id}>
                    {item.values?.[col.id] || '-'}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>

        {/* 하단 정보 */}
        <div className="insp-footer-section">
          {/* 비고 */}
          <div className="insp-notes-box">
            <div className="font-bold mb-2">{documentTemplate.notesLabel || '비고'}</div>
            <div>{notes || ' '}</div>
          </div>

          {/* 종합 판정 */}
          <div className="insp-judgment-box">
            <div className="insp-judgment-label">{documentTemplate.judgmentLabel || '종합판정'}</div>
            <div className="insp-judgment-value">
              {judgment || '[ 판정 대기 ]'}
            </div>
          </div>
        </div>

        {/* 회사 정보 */}
        {documentTemplate.companyAddress || documentTemplate.companyPhone ? (
          <div className="mt-8 text-center text-sm text-muted-foreground">
            <div className="font-bold text-base text-black mb-2">{documentTemplate.companyName}</div>
            {documentTemplate.companyAddress && <div>{documentTemplate.companyAddress}</div>}
            {documentTemplate.companyPhone && <div>TEL: {documentTemplate.companyPhone}</div>}
          </div>
        ) : null}

      </div>
    </>
  );
}
