"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 BendingInspectionData {
  documentNo: string;
  productName: string;
  productType: '필재' | '스크린';
  specification: string;
  client: string;
  siteName: string;
  itemName: string;
  lotNo: string;
  lotSize: string;
  inspectionDate: string;
  inspector: string;
  finishType: string;
  susFinish: string;
  approvers: {
    writer?: string;
    reviewer?: string;
    approver?: string;
  };
  // 중간검사 기준서 정보
  standardInfo: {
    caseFinish: {
      appearance: { 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 };
    };
    bandFinish: {
      appearance: { 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: {
    category: string;
    itemName: string;
    type: string;
    bendState: '양호' | '불량';
    length: number;
    conductance1: string;
    measured1: number | null;
    point: number;
    conductance2: string;
    measured2: number | null;
    result: '적합' | '부적합';
  }[];
  notes: string;
  overallResult: '합격' | '불합격';
}

// Mock 데이터
export const MOCK_BENDING_INSPECTION: BendingInspectionData = {
  documentNo: 'KDQP-01-007',
  productName: '절곡품',
  productType: '스크린',
  specification: '□ 필재 □ 스크린',
  client: '경동기업',
  siteName: '용산고등학교(4호)',
  itemName: 'KWE01',
  lotNo: 'KD-WE-251015-01-(3)',
  lotSize: '11 개소',
  inspectionDate: '2025.',
  inspector: '',
  finishType: '마감유형',
  susFinish: 'SUS마감',
  approvers: {
    writer: '전진',
    reviewer: '',
    approver: '',
  },
  standardInfo: {
    caseFinish: {
      appearance: {
        criteria: '사용상 해로운 결함이 없을 것',
        method: '절무검사',
        frequency: 'n = L, c = 0',
        regulation: 'KS F 4510 5.1항',
      },
      dimensions: {
        criteria: '길이\n도전차수 ± 4',
        method: '체크검사',
        frequency: 'n = L, c = 0',
        regulation: 'KS F 4510 7항\n외주 자재검규',
      },
      inspection: {
        criteria: '도전차수 ± 2',
        method: '',
        frequency: '',
        regulation: '',
      },
    },
    bandFinish: {
      appearance: {
        criteria: '사용상 해로운 결함이 없을 것',
        method: '절무검사',
        frequency: 'n = L, c = 0',
        regulation: 'KS F 4510 5.1항',
      },
      dimensions: {
        criteria: '길이\n도전차수 ± 4\nW50 : 50 ± 5\nW80 : 80 ± 5',
        method: '',
        frequency: '',
        regulation: 'KS F 4510 7항\n외 9',
      },
      inspection: {
        criteria: '도전차수 ± 2',
        method: '체크검사',
        frequency: '',
        regulation: '',
      },
    },
  },
  inspectionData: [
    { category: '필재\n(K0150)', itemName: '가이드레일', type: '아연판', bendState: '양호', length: 4300, conductance1: 'N/A', measured1: null, point: 30, conductance2: '', measured2: null, result: '적합' },
    { category: '', itemName: '', type: '', bendState: '양호', length: 0, conductance1: '', measured1: null, point: 78, conductance2: '', measured2: null, result: '적합' },
    { category: '', itemName: '', type: '', bendState: '양호', length: 0, conductance1: '', measured1: null, point: 25, conductance2: '', measured2: null, result: '적합' },
    { category: '', itemName: '', type: '', bendState: '양호', length: 0, conductance1: '', measured1: null, point: 45, conductance2: '', measured2: null, result: '적합' },
  ],
  notes: '',
  overallResult: '합격',
};

interface BendingInspectionDocumentProps {
  data?: BendingInspectionData;
}

export const BendingInspectionDocument = ({ data = MOCK_BENDING_INSPECTION }: BendingInspectionDocumentProps) => {
  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">
              <span className={data.productType === '필재' ? 'font-bold' : ''}>☐ 필재</span>
              {' '}
              <span className={data.productType === '스크린' ? 'font-bold' : ''}>☑ 스크린</span>
            </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>
          <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.itemName}</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.susFinish}</td>
          </tr>
        </tbody>
      </table>

      {/* 중간검사 기준서 - 케이스/커버마감재 */}
      <table className="w-full border-collapse mb-2 text-xs">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 px-2 py-1 w-24" rowSpan={4}>케이스커버<br/>마감재<br/>중간검사<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={3}>
              <div className="w-14 h-16 mx-auto border border-gray-300 bg-gray-50 flex items-center justify-center text-[8px] text-gray-400">
                케이스<br/>도해
              </div>
            </td>
            <td className="border border-gray-400 px-1 py-1 text-center">겉모양</td>
            <td className="border border-gray-400 px-1 py-1">{data.standardInfo.caseFinish.appearance.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center">{data.standardInfo.caseFinish.appearance.method}</td>
            <td className="border border-gray-400 px-1 py-1 text-center whitespace-pre-line">{data.standardInfo.caseFinish.appearance.frequency}</td>
            <td className="border border-gray-400 px-1 py-1 text-center text-[9px]">{data.standardInfo.caseFinish.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.caseFinish.dimensions.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center">{data.standardInfo.caseFinish.dimensions.method}</td>
            <td className="border border-gray-400 px-1 py-1 text-center whitespace-pre-line">{data.standardInfo.caseFinish.dimensions.frequency}</td>
            <td className="border border-gray-400 px-1 py-1 text-center text-[9px] whitespace-pre-line">{data.standardInfo.caseFinish.dimensions.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">{data.standardInfo.caseFinish.inspection.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"></td>
          </tr>
        </tbody>
      </table>

      {/* 중간검사 기준서 - 밴딩마감재 */}
      <table className="w-full border-collapse mb-4 text-xs">
        <tbody>
          <tr>
            <td className="border border-gray-400 px-2 py-1 w-24 bg-gray-100 text-center align-middle" rowSpan={3}>밴딩마감재<br/>중간검사<br/>기준서</td>
            <td className="border border-gray-400 p-1 text-center align-middle w-16" rowSpan={3}>
              <div className="w-14 h-12 mx-auto border border-gray-300 bg-gray-50 flex items-center justify-center text-[8px] text-gray-400">
                밴딩<br/>도해
              </div>
            </td>
            <td className="border border-gray-400 px-1 py-1 text-center w-16">겉모양</td>
            <td className="border border-gray-400 px-1 py-1">{data.standardInfo.bandFinish.appearance.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center w-14">{data.standardInfo.bandFinish.appearance.method}</td>
            <td className="border border-gray-400 px-1 py-1 text-center w-14 whitespace-pre-line">{data.standardInfo.bandFinish.appearance.frequency}</td>
            <td className="border border-gray-400 px-1 py-1 text-center w-24 text-[9px]">{data.standardInfo.bandFinish.appearance.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.bandFinish.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] whitespace-pre-line">{data.standardInfo.bandFinish.dimensions.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">{data.standardInfo.bandFinish.inspection.criteria}</td>
            <td className="border border-gray-400 px-1 py-1 text-center">{data.standardInfo.bandFinish.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"></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}>분류</th>
            <th className="border border-gray-400 px-1 py-1" rowSpan={2}>제품명</th>
            <th className="border border-gray-400 px-1 py-1" rowSpan={2}>타입</th>
            <th className="border border-gray-400 px-1 py-1" rowSpan={2}>절곡상태</th>
            <th className="border border-gray-400 px-1 py-1" colSpan={3}>치수 [mm]</th>
            <th className="border border-gray-400 px-1 py-1" colSpan={2}>⓪ 건전</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">측정값</th>
            <th className="border border-gray-400 px-1 py-1">POINT</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 whitespace-pre-line">{item.category}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.itemName}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.type}</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.length > 0 ? formatNumber(item.length) : ''}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.conductance1}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.measured1}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.point}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">{item.conductance2}</td>
              <td className="border border-gray-400 px-1 py-1 text-center">
                ☐ 적합 ☐ 부적합
              </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-01</div>
      </div>
    </div>
  );
};