"use client";

/**
 * 제품검사 성적서 문서 컴포넌트
 *
 * 공통 컴포넌트 사용:
 * - DocumentHeader: default 레이아웃 + customApproval (QualityApprovalTable)
 */

import React from 'react';
import { DocumentHeader, QualityApprovalTable } from '@/components/document-system';

// 제품검사 성적서 데이터 타입
export interface ProductInspectionData {
  documentNo: string;
  deliveryName: string;
  productName: string;
  client: string;
  siteName: string;
  lotNo: string;
  lotSize: string;
  inspectionDate: string;
  inspector: string;
  approvers: {
    writer?: string;
    reviewer?: string;
    approver?: string;
  };
  productImage?: string;
  inspectionItems: {
    id: number;
    name: string;
    criteria: string;
    method: string;
    frequency: string;
    result: '적합' | '부적합' | '';
  }[];
  notes: string;
  overallResult: '합격' | '불합격';
}

// Mock 데이터
export const MOCK_PRODUCT_INSPECTION: ProductInspectionData = {
  documentNo: 'KDQP-01-003',
  deliveryName: '스크린 방화셔터',
  productName: 'WY-SC780 방화셔터',
  client: '삼성물산(주)',
  siteName: '용산고등학교(4호)',
  lotNo: 'KD-SA-251218-01',
  lotSize: 'EA',
  inspectionDate: '2023.',
  inspector: '',
  approvers: {
    writer: '김검사',
    reviewer: '',
    approver: '박승인',
  },
  productImage: '',
  inspectionItems: [
    {
      id: 1,
      name: '가공상태',
      criteria: '사용상 해로운 결함이 없을 것',
      method: '',
      frequency: '',
      result: '적합',
    },
    {
      id: 2,
      name: '외관검사',
      criteria: '내용물이 타 견고하게 결합되어야 한\n(찌그러지 않아야 함)',
      method: '',
      frequency: '',
      result: '적합',
    },
    {
      id: 3,
      name: '절단면',
      criteria: '밴드시트 전고무에 프라이머와\n젤리이어야 함',
      method: '육안검사',
      frequency: '',
      result: '적합',
    },
    {
      id: 4,
      name: '도포상태',
      criteria: '용접부위에 락터스베이\n도포하여야 함',
      method: '',
      frequency: '',
      result: '적합',
    },
    {
      id: 5,
      name: '조립\n(W4-SC780 전제품 확인)',
      criteria: '간섭부위 프라이머 락터스베이(케노x, 깔대기) W-80스크린',
      method: '',
      frequency: '',
      result: '적합',
    },
    {
      id: 6,
      name: '슬릿',
      criteria: '현장이동 ± 30mm',
      method: '',
      frequency: '',
      result: '',
    },
    {
      id: 7,
      name: '규격치수\n(슬릿/가이드레일)',
      criteria: '현장이동 ± 30mm\n10 ± 6mm(측정치), (총 높이 152 이상)',
      method: '줄자/측정기',
      frequency: '',
      result: '',
    },
    {
      id: 8,
      name: '마감처리',
      criteria: '가이드레일과 하단가이드를 높이 25mm이상 처리 있음\n20mm 균형케이스 화보완연 손',
      method: '',
      frequency: '',
      result: '',
    },
    {
      id: 9,
      name: '내벽시트',
      criteria: '프린팅\n용지 치 상부 및 완전보완시 작업하위',
      method: '',
      frequency: '',
      result: '',
    },
    {
      id: 10,
      name: '마감시트',
      criteria: '4-5cycle\n젤 두께 3 ~ 7cycle',
      method: '',
      frequency: '',
      result: '',
    },
    {
      id: 11,
      name: '배색시트',
      criteria: '2차 시트 길이 및 완전보완시 작업하위',
      method: '',
      frequency: '',
      result: '',
    },
  ],
  notes: '1.내벽시트, 마감시트, 배색시트에 내용기재라, 시트 관리업무(업무인력)시 사용, 견적위함, □ 관련사항을 기록하며',
  overallResult: '합격',
};

interface ProductInspectionDocumentProps {
  data?: ProductInspectionData;
}

export const ProductInspectionDocument = ({ data = MOCK_PRODUCT_INSPECTION }: ProductInspectionDocumentProps) => {
  return (
    <div className="bg-white p-8 w-full text-sm shadow-sm print:shadow-none">
      {/* 문서 헤더 (공통 컴포넌트) */}
      <DocumentHeader
        title="제 품 검 사 성 적 서"
        logo={{ text: 'KD', subtext: '경동기업\nKYUNGDONG COMPANY' }}
        customApproval={
          <QualityApprovalTable
            type="4col"
            approvers={data.approvers}
          />
        }
      />

      {/* 기본 정보 테이블 */}
      <table className="w-full border-collapse mb-4 text-xs">
        <tbody>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 w-20 font-medium">납품명</td>
            <td className="border border-gray-400 px-3 py-2">{data.deliveryName}</td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 w-20 font-medium">제품 LOT NO</td>
            <td className="border border-gray-400 px-3 py-2">{data.lotNo}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 font-medium">제품명</td>
            <td className="border border-gray-400 px-3 py-2">{data.productName}</td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 font-medium">로트크기</td>
            <td className="border border-gray-400 px-3 py-2">{data.lotSize}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 font-medium">발주처</td>
            <td className="border border-gray-400 px-3 py-2">{data.client}</td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 font-medium">검사일자</td>
            <td className="border border-gray-400 px-3 py-2">{data.inspectionDate}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 font-medium">현장명</td>
            <td className="border border-gray-400 px-3 py-2">{data.siteName}</td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 font-medium">검사자</td>
            <td className="border border-gray-400 px-3 py-2">{data.inspector}</td>
          </tr>
        </tbody>
      </table>

      {/* 제품사진 및 검사항목 */}
      <div className="flex gap-4 mb-4">
        {/* 제품사진 영역 */}
        <div className="w-48 shrink-0">
          <div className="border border-gray-400 h-36 flex items-center justify-center bg-gray-50">
            {data.productImage ? (
              <img src={data.productImage} alt="제품 사진" className="max-w-full max-h-full object-contain" />
            ) : (
              <div className="text-center text-gray-400 text-xs">
                <div className="mb-2">제품사진</div>
                <div className="text-[10px]">마이크로 폼 긴 수 제품<br/>188 128 158 화면</div>
              </div>
            )}
          </div>
        </div>

        {/* 검사기준 영역 */}
        <div className="flex-1 text-xs text-gray-500">
          <p>(하단참조)</p>
          <p>하단참조</p>
        </div>
      </div>

      {/* 검사 항목 테이블 */}
      <table className="w-full border-collapse text-xs mb-4">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 px-2 py-2 w-10">No</th>
            <th className="border border-gray-400 px-2 py-2 w-24">검사항목</th>
            <th className="border border-gray-400 px-2 py-2">검사기준</th>
            <th className="border border-gray-400 px-2 py-2 w-20">검사방법</th>
            <th className="border border-gray-400 px-2 py-2 w-16">검사주기</th>
            <th className="border border-gray-400 px-2 py-2 w-16">판정</th>
          </tr>
        </thead>
        <tbody>
          {data.inspectionItems.map((item) => (
            <tr key={item.id}>
              <td className="border border-gray-400 px-2 py-2 text-center">{item.id}</td>
              <td className="border border-gray-400 px-2 py-2 text-center whitespace-pre-line">{item.name}</td>
              <td className="border border-gray-400 px-2 py-2 whitespace-pre-line">{item.criteria}</td>
              <td className="border border-gray-400 px-2 py-2 text-center">{item.method}</td>
              <td className="border border-gray-400 px-2 py-2 text-center">{item.frequency}</td>
              <td className="border border-gray-400 px-2 py-2 text-center">
                {item.result && (
                  <span className={item.result === '적합' ? 'text-blue-600' : 'text-red-600'}>
                    ☑ {item.result === '적합' ? '적합' : '부적합'} ☐ {item.result === '적합' ? '부적합' : '적합'}
                  </span>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {/* 특기사항 */}
      <div className="border border-gray-400 mb-4">
        <div className="bg-gray-100 px-3 py-1 text-xs font-medium border-b border-gray-400">【특기사항】</div>
        <div className="px-3 py-2 text-xs text-gray-600 min-h-[40px]">{data.notes}</div>
      </div>

      {/* 문서번호 및 종합판정 */}
      <div className="flex justify-between items-end">
        <div className="text-xs text-gray-500">{data.documentNo}</div>
        <div className="border border-gray-400">
          <div className="bg-gray-100 px-4 py-1 text-center text-xs font-medium border-b border-gray-400">종합판정</div>
          <div className={`px-8 py-2 text-center text-sm font-bold ${data.overallResult === '합격' ? 'text-blue-600' : 'text-red-600'}`}>
            {data.overallResult}
          </div>
        </div>
        <div className="text-xs text-gray-500">서식관리기준</div>
      </div>
    </div>
  );
};