"use client";

/**
 * 슬랫 중간검사 성적서 문서 컴포넌트
 *
 * 공통 컴포넌트 사용:
 * - DocumentHeader: quality 레이아웃 + customApproval (QualityApprovalTable)
 */

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

// 슬랫 중간검사 성적서 데이터 타입
export interface SlatInspectionData {
  documentNo: string;
  productName: string;
  specification: string;
  client: string;
  siteName: string;
  lotNo: string;
  lotSize: string;
  inspectionDate: string;
  inspector: string;
  approvers: {
    writer?: string;
    reviewer?: string;
    approver?: string;
  };
  // 중간검사 기준서 정보
  standardInfo: {
    appearance: { criteria: string; method: string; frequency: string; regulation: string };
    assembly: { criteria: string; method: string; frequency: string; regulation: string };
    dimensions: { criteria: string; method: string; frequency: string; regulation: string };
    inspection: { criteria: string; method: string; frequency: string; regulation: string };
  };
  // 중간검사 DATA
  inspectionData: {
    serialNo: string;
    processState: '양호' | '불량';
    assemblyState: '양호' | '불량';
    height1: { standard: number; measured: number };
    height2: { standard: number; measured: number };
    bandLength: { conductance: string; measured: number };
    result: '적합' | '부적합';
  }[];
  notes: string;
  overallResult: '합격' | '불합격';
}

// Mock 데이터
export const MOCK_SLAT_INSPECTION: SlatInspectionData = {
  documentNo: 'KDQP-01-008',
  productName: '슬랫',
  specification: '와이어 클러치 크립지름',
  client: '주일',
  siteName: '용산고등학교(4호)',
  lotNo: 'KD-WE-251015-01-(3)',
  lotSize: '11 개소',
  inspectionDate: '2025.',
  inspector: '',
  approvers: {
    writer: '전진',
    reviewer: '',
    approver: '',
  },
  standardInfo: {
    appearance: {
      criteria: '사용상 해로운 결함이 없을 것',
      method: '',
      frequency: 'n = 1, c = 0',
      regulation: 'KS F 4510 5.1항',
    },
    assembly: {
      criteria: '밴드시트 읍동에 의해\n견고하게 조립되어야 함',
      method: '확인점검',
      frequency: '',
      regulation: 'KS F 4510 9항',
    },
    dimensions: {
      criteria: '용접부위에 락터스베이\n도포하여야 함',
      method: '',
      frequency: '',
      regulation: '자체규정',
    },
    inspection: {
      criteria: '16.5 ± 1\n14.5 ± 1\n도전차수+(밴드마감재) ± 4',
      method: '체크검사',
      frequency: '',
      regulation: 'KS F 4510 7항\n외 9',
    },
  },
  inspectionData: [
    { serialNo: '01', processState: '양호', assemblyState: '양호', height1: { standard: 16.5, measured: 14.5 }, height2: { standard: 14.5, measured: 14.5 }, bandLength: { conductance: '4,510', measured: 4510 }, result: '적합' },
    { serialNo: '02', processState: '양호', assemblyState: '양호', height1: { standard: 16.5, measured: 14.5 }, height2: { standard: 14.5, measured: 14.5 }, bandLength: { conductance: '', measured: 0 }, result: '적합' },
    { serialNo: '03', processState: '양호', assemblyState: '양호', height1: { standard: 16.5, measured: 14.5 }, height2: { standard: 14.5, measured: 14.5 }, bandLength: { conductance: '', measured: 0 }, result: '적합' },
    { serialNo: '04', processState: '양호', assemblyState: '양호', height1: { standard: 16.5, measured: 14.5 }, height2: { standard: 14.5, measured: 14.5 }, bandLength: { conductance: '', measured: 0 }, result: '적합' },
    { serialNo: '05', processState: '양호', assemblyState: '양호', height1: { standard: 16.5, measured: 14.5 }, height2: { standard: 14.5, measured: 14.5 }, bandLength: { conductance: '', measured: 0 }, result: '적합' },
  ],
  notes: '',
  overallResult: '합격',
};

interface SlatInspectionDocumentProps {
  data?: SlatInspectionData;
}

export const SlatInspectionDocument = ({ data = MOCK_SLAT_INSPECTION }: SlatInspectionDocumentProps) => {
  return (
    <div className="bg-white p-8 w-full text-sm shadow-sm print:shadow-none">
      {/* 문서 헤더 (공통 컴포넌트) */}
      <DocumentHeader
        title="슬랫"
        subtitle="중간검사 성적서"
        layout="quality"
        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.productName}</td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 w-24 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.specification}</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>

      {/* 중간검사 기준서 */}
      <table className="w-full border-collapse mb-4 text-xs">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 px-2 py-1 w-24" rowSpan={5}>중간검사<br/>기준서</th>
            <th className="border border-gray-400 px-2 py-1 w-16">도해</th>
            <th className="border border-gray-400 px-2 py-1 w-16">검사항목</th>
            <th className="border border-gray-400 px-2 py-1">검사기준</th>
            <th className="border border-gray-400 px-2 py-1 w-14">검사방법</th>
            <th className="border border-gray-400 px-2 py-1 w-14">검사주기</th>
            <th className="border border-gray-400 px-2 py-1 w-24">관련규정</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td className="border border-gray-400 p-1 text-center align-middle" rowSpan={4}>
              {/* 도해 이미지 영역 */}
              <div className="w-14 h-20 mx-auto border border-gray-300 bg-gray-50 flex items-center justify-center">
                <div className="text-center text-gray-400">
                  <div className="flex flex-col items-center gap-1">
                    <span className="w-3 h-3 border border-gray-400 rounded-full flex items-center justify-center text-[6px]">1</span>
                    <div className="w-8 h-1 bg-gray-300"></div>
                    <span className="w-3 h-3 border border-gray-400 rounded-full flex items-center justify-center text-[6px]">2</span>
                    <div className="w-8 h-6 border border-gray-300"></div>
                  </div>
                </div>
              </div>
            </td>
            <td className="border border-gray-400 px-1 py-1 text-center">가공상태<br/>(겉모양)</td>
            <td className="border border-gray-400 px-1 py-1">{data.standardInfo.appearance.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center"></td>
            <td className="border border-gray-400 px-1 py-1 text-center">{data.standardInfo.appearance.frequency}</td>
            <td className="border border-gray-400 px-1 py-1 text-center text-[9px]">{data.standardInfo.appearance.regulation}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-1 py-1 text-center"></td>
            <td className="border border-gray-400 px-1 py-1 whitespace-pre-line">{data.standardInfo.assembly.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center">{data.standardInfo.assembly.method}</td>
            <td className="border border-gray-400 px-1 py-1 text-center"></td>
            <td className="border border-gray-400 px-1 py-1 text-center text-[9px]">{data.standardInfo.assembly.regulation}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-1 py-1 text-center"></td>
            <td className="border border-gray-400 px-1 py-1 whitespace-pre-line">{data.standardInfo.dimensions.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center"></td>
            <td className="border border-gray-400 px-1 py-1 text-center"></td>
            <td className="border border-gray-400 px-1 py-1 text-center text-[9px]">{data.standardInfo.dimensions.regulation}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-1 py-1 text-center">치수<br/>(mm)</td>
            <td className="border border-gray-400 px-1 py-1 whitespace-pre-line">{data.standardInfo.inspection.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center">{data.standardInfo.inspection.method}</td>
            <td className="border border-gray-400 px-1 py-1 text-center"></td>
            <td className="border border-gray-400 px-1 py-1 text-center text-[9px] whitespace-pre-line">{data.standardInfo.inspection.regulation}</td>
          </tr>
        </tbody>
      </table>

      {/* 중간검사 DATA */}
      <div className="mb-2 text-xs font-medium">중간검사 DATA</div>
      <table className="w-full border-collapse text-xs mb-4">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 px-1 py-1" rowSpan={2}>일련<br/>번호</th>
            <th className="border border-gray-400 px-1 py-1" colSpan={2}>검사항</th>
            <th className="border border-gray-400 px-1 py-1" colSpan={4}>치수 [mm]</th>
            <th className="border border-gray-400 px-1 py-1" rowSpan={2}>판정</th>
          </tr>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 px-1 py-1">가공상태</th>
            <th className="border border-gray-400 px-1 py-1">조립상태</th>
            <th className="border border-gray-400 px-1 py-1">⓪ 높이<br/>기준치</th>
            <th className="border border-gray-400 px-1 py-1">측정값</th>
            <th className="border border-gray-400 px-1 py-1">⓪ 길이 (밴드마감재)<br/>기준치</th>
            <th className="border border-gray-400 px-1 py-1">측정값</th>
          </tr>
        </thead>
        <tbody>
          {data.inspectionData.map((item, index) => (
            <tr key={index}>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.serialNo}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">
                ☐ 양호 ☐ 불량
              </td>
              <td className="border border-gray-400 px-1 py-1 text-center">
                ☐ 양호 ☐ 불량
              </td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.height1.standard} ± 1</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.height1.measured}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.bandLength.conductance}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.bandLength.measured > 0 ? formatNumber(item.bandLength.measured) : ''}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">
                ☐ 적합 ☐ 부<br/>적합
              </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-[30px]">{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">KDPS-10-02</div>
      </div>
    </div>
  );
};
