/**
 * 검사 문서 미리보기
 * 발주서 톤앤매너 기준으로 A4 용지 형태 미리보기 제공
 */

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

interface InspectionDocumentPreviewProps {
  template: InspectionStandard['documentTemplate'];
  inspectionType: string;
}

export function InspectionDocumentPreview({ template, inspectionType }: InspectionDocumentPreviewProps) {
  const inspectionTypeName = 
    inspectionType === 'incoming' ? '수입검사' : 
    inspectionType === 'process' ? '중간검사' : '제품검사';

  // 디버깅: 결재라인 데이터 확인
  console.log('📋 미리보기 템플릿 데이터:', template);
  console.log('👥 결재라인 데이터:', template.approvalLines);
  console.log('👥 결재라인 개수:', template.approvalLines?.length);

  return (
    <>
      <style>{`
        @media print {
          @page {
            size: A4 portrait;
            margin: 10mm;
          }
          
          body {
            background: white !important;
          }
          
          #inspection-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-logo-box {
          width: 120px;
          height: 100px;
          border: 2px solid #000;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background: linear-gradient(135deg, #0066cc 0%, #003d99 100%);
          color: white;
        }
        
        .insp-logo-text {
          font-size: 28px;
          font-weight: 700;
          letter-spacing: 2px;
        }
        
        .insp-logo-sub {
          font-size: 11px;
          margin-top: 5px;
          letter-spacing: 3px;
        }
        
        .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-approval-box {
          width: 100%;
          border: none;
          display: grid;
          grid-template-columns: 60px repeat(3, 1fr);
        }
        
        .insp-approval-merged-vertical-cell {
          border-right: 1px solid #000;
          padding: 4px;
          text-align: center;
          font-weight: 600;
          font-size: 11px;
          background: white;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        .insp-approval-column {
          display: flex;
          flex-direction: column;
          border-right: 1px solid #000;
        }
        
        .insp-approval-column:last-child {
          border-right: none;
        }
        
        .insp-approval-position {
          border-bottom: 1px solid #000;
          padding: 8px;
          text-align: center;
          font-weight: 600;
          font-size: 12px;
          background: white;
        }
        
        .insp-approval-signature {
          border-bottom: 1px solid #000;
          padding: 8px;
          text-align: center;
          font-size: 11px;
          height: 50px;
          background: white;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        .insp-approval-department {
          padding: 6px;
          text-align: center;
          font-weight: 600;
          font-size: 11px;
          background: white;
        }
        
        .insp-section-table {
          width: 100%;
          border-collapse: collapse;
          border: 2px solid #000;
          margin-bottom: 15px;
        }
        
        .insp-section-header {
          background: #e8e8e8;
          border: 1px solid #666;
          padding: 8px;
          text-align: center;
          font-weight: 700;
          font-size: 13px;
          width: 120px;
        }
        
        .insp-section-content {
          border: 1px solid #666;
          padding: 8px;
          font-size: 12px;
        }
        
        .insp-items-table {
          width: 100%;
          border-collapse: collapse;
          border: 2px solid #000;
          margin-bottom: 15px;
        }
        
        .insp-items-table th {
          background: #e8e8e8;
          border: 1px solid #666;
          padding: 8px 4px;
          text-align: center;
          font-weight: 700;
          font-size: 11px;
        }
        
        .insp-items-table td {
          border: 1px solid #666;
          padding: 6px 4px;
          text-align: center;
          font-size: 11px;
        }
        
        .insp-notes-section {
          border: 2px solid #000;
          margin-bottom: 15px;
        }
        
        .insp-notes-header {
          background: #e8e8e8;
          border-bottom: 2px solid #000;
          padding: 8px;
          font-weight: 700;
          font-size: 13px;
        }
        
        .insp-notes-content {
          padding: 12px;
          min-height: 80px;
        }
        
        .insp-judgment-table {
          width: 100%;
          border-collapse: collapse;
          border: 2px solid #000;
        }
        
        .insp-judgment-header {
          background: #e8e8e8;
          border: 1px solid #666;
          padding: 8px;
          text-align: center;
          font-weight: 700;
          font-size: 13px;
          width: 120px;
        }
        
        .insp-judgment-content {
          border: 1px solid #666;
          padding: 10px;
          font-size: 12px;
        }
        
        .insp-checkbox {
          display: inline-block;
          width: 16px;
          height: 16px;
          border: 2px solid #000;
          margin-right: 6px;
          vertical-align: middle;
        }
        
        .insp-signature-section {
          margin-top: 30px;
          padding-top: 20px;
          border-top: 1px solid #ccc;
        }
      `}</style>
      
      <div className="inspection-doc" id="inspection-content">
        {/* 헤더 - 로고, 타이틀, 결재라인을 한 줄에 배치 */}
        <div className="insp-header">
          {/* 제목 */}
          <div className="insp-title">
            <h1>{template.title}</h1>
          </div>
          
          {/* 결재라인 */}
          {template.approvalLines.length > 0 && (
            <div className="insp-approval-section">
              <div className="insp-approval-box">
                <div className="insp-approval-merged-vertical-cell">
                  결<br/>재
                </div>
                
                {/* 각 결재자를 세로 column으로 배치 */}
                {[0, 1, 2].map((index) => (
                  <div key={index} className="insp-approval-column">
                    {/* 직책 */}
                    <div className="insp-approval-position">
                      {template.approvalLines[index]?.position || (index === 0 ? '작성' : index === 1 ? '검토' : '승인')}
                    </div>
                    {/* 서명란 */}
                    <div className="insp-approval-signature">
                      {template.approvalLines[index]?.name || ''}
                    </div>
                    {/* 부서 */}
                    <div className="insp-approval-department">
                      {template.approvalLines[index]?.department || ''}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* 회사 정보 */}
        {(template.companyAddress || template.companyPhone) && (
          <div style={{ textAlign: 'right', fontSize: '11px', marginBottom: '15px', color: '#666' }}>
            {template.companyAddress && <div>{template.companyAddress}</div>}
            {template.companyPhone && <div>TEL: {template.companyPhone}</div>}
          </div>
        )}

        {/* 기본 정보 */}
        {template.basicInfoFields.length > 0 && (
          <table className="insp-section-table">
            <tbody>
              {template.basicInfoFields.map((field, index) => {
                const isEven = index % 2 === 0;
                if (isEven && index + 1 < template.basicInfoFields.length) {
                  const nextField = template.basicInfoFields[index + 1];
                  return (
                    <tr key={field.id}>
                      <td className="insp-section-header">{field.label}</td>
                      <td className="insp-section-content">{field.value || '\u00A0'}</td>
                      <td className="insp-section-header">{nextField.label}</td>
                      <td className="insp-section-content">{nextField.value || '\u00A0'}</td>
                    </tr>
                  );
                } else if (!isEven) {
                  return null;
                } else {
                  return (
                    <tr key={field.id}>
                      <td className="insp-section-header">{field.label}</td>
                      <td className="insp-section-content" colSpan={3}>{field.value || '\u00A0'}</td>
                    </tr>
                  );
                }
              })}
            </tbody>
          </table>
        )}

        {/* 검사항목 테이블 */}
        {template.inspectionColumns.length > 0 && (
          <table className="insp-items-table">
            <thead>
              <tr>
                {template.inspectionColumns.map(col => (
                  <th key={col.id} style={{ width: col.width }}>
                    {col.name}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {template.inspectionItems.length > 0 ? (
                template.inspectionItems.map(item => (
                  <tr key={item.id}>
                    {template.inspectionColumns.map(col => (
                      <td key={col.id}>
                        {item.values[col.id] || '\u00A0'}
                      </td>
                    ))}
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={template.inspectionColumns.length} style={{ padding: '30px', textAlign: 'center', color: '#999' }}>
                    검사항목이 없습니다
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        )}

        {/* 비고 */}
        <div className="insp-notes-section">
          <div className="insp-notes-header">
            {template.notesLabel || '비고'}
          </div>
          <div className="insp-notes-content">
            {/* 비고 입력 영역 */}
          </div>
        </div>

        {/* 종합 판정 */}
        <table className="insp-judgment-table">
          <tbody>
            <tr>
              <td className="insp-judgment-header">
                {template.judgmentLabel || '종합판정'}
              </td>
              <td className="insp-judgment-content">
                {template.judgmentOptions && template.judgmentOptions.length > 0 ? (
                  <div style={{ display: 'flex', gap: '20px', alignItems: 'center' }}>
                    {template.judgmentOptions.map((option, idx) => (
                      <div key={idx} style={{ display: 'flex', alignItems: 'center' }}>
                        <span className="insp-checkbox"></span>
                        <span>{option}</span>
                      </div>
                    ))}
                  </div>
                ) : (
                  '\u00A0'
                )}
              </td>
            </tr>
          </tbody>
        </table>

        {/* 서명 영역 */}
        <div className="insp-signature-section">
          <table style={{ width: '100%', fontSize: '12px' }}>
            <tbody>
              <tr>
                <td style={{ width: '33%', textAlign: 'center', paddingBottom: '30px' }}>
                  <div style={{ marginBottom: '10px', color: '#666' }}>검사일</div>
                  <div style={{ borderBottom: '1px solid #000', display: 'inline-block', minWidth: '150px', paddingBottom: '5px' }}>
                    년    월    일
                  </div>
                </td>
                <td style={{ width: '33%', textAlign: 'center', paddingBottom: '30px' }}>
                  <div style={{ marginBottom: '10px', color: '#666' }}>검사자</div>
                  <div style={{ borderBottom: '1px solid #000', display: 'inline-block', minWidth: '150px', paddingBottom: '5px' }}>
                    &nbsp;
                  </div>
                </td>
                <td style={{ width: '33%', textAlign: 'center', paddingBottom: '30px' }}>
                  <div style={{ marginBottom: '10px', color: '#666' }}>확인자</div>
                  <div style={{ borderBottom: '1px solid #000', display: 'inline-block', minWidth: '150px', paddingBottom: '5px' }}>
                    &nbsp;
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}