'use client';

/**
 * 슬랫 조인트바 중간검사성적서
 *
 * 기획서 기준:
 * - 제목: "중간검사성적서 (조인트바)"
 * - 결재란: 작성/승인/승인/승인
 * - 기본 정보: 제품명/슬랫, 규격/슬랫, 수주처, 현장명 / 제품 LOT NO, 부서, 검사일자, 검사자
 * - ■ 중간검사 기준서 KOPS-20: 도해 IMG + 치수 기준 (43.1 ± 0.5 등)
 * - ■ 중간검사 DATA: No, 가공상태, 조립상태, ①높이(기준치/측정값),
 *   ②높이(기준치/측정값), ③길이(기준치/측정값), ④간격(기준치/측정값), 판정
 * - 부적합 내용 / 종합판정 (자동)
 */

import { useState, useCallback, useMemo, forwardRef, useImperativeHandle, useEffect } from 'react';
import type { WorkOrder } from '../types';
import type { InspectionData } from '@/components/production/WorkerScreen/InspectionInputModal';
import type { WorkItemData } from '@/components/production/WorkerScreen/types';
import type { InspectionDataMap } from './InspectionReportModal';
import type { InspectionSetting } from '@/types/process';
import {
  type CheckStatus,
  type InspectionContentRef,
  convertToCheckStatus,
  getFullDate,
  getToday,
  getOrderInfo,
  calculateOverallResult,
  INPUT_CLASS,
  DEFAULT_ROW_COUNT,
  CheckStatusCell,
  JudgmentCell,
  InspectionLayout,
  InspectionFooter,
  InspectionStandardSection,
} from './inspection-shared';

export type { InspectionContentRef };

export interface SlatJointBarInspectionContentProps {
  data: WorkOrder;
  readOnly?: boolean;
  inspectionData?: InspectionData;
  workItems?: WorkItemData[];
  inspectionDataMap?: InspectionDataMap;
  inspectionSetting?: InspectionSetting;
  schematicImage?: string;
  inspectionStandardImage?: string;
}

interface InspectionRow {
  id: number;
  itemId?: string;
  itemName?: string;
  processStatus: CheckStatus;
  assemblyStatus: CheckStatus;
  height1Standard: string;
  height1Measured: string;
  height2Standard: string;
  height2Measured: string;
  lengthDesign: string;
  lengthMeasured: string;
  intervalStandard: string;
  intervalMeasured: string;
}

function buildRow(i: number, workItems?: WorkItemData[], inspectionDataMap?: InspectionDataMap): InspectionRow {
  const item = workItems?.[i];
  const itemData = item && inspectionDataMap?.get(item.id);
  return {
    id: i + 1,
    itemId: item?.id,
    itemName: item?.itemName,
    processStatus: itemData ? convertToCheckStatus(itemData.processingStatus) : null,
    assemblyStatus: itemData ? convertToCheckStatus(itemData.assemblyStatus) : null,
    height1Standard: '43.1 \u00b1 0.5',
    height1Measured: '',
    height2Standard: '14.5 \u00b1 1',
    height2Measured: '',
    lengthDesign: '',
    lengthMeasured: '',
    intervalStandard: '150 \u00b1 4',
    intervalMeasured: '',
  };
}

export const SlatJointBarInspectionContent = forwardRef<InspectionContentRef, SlatJointBarInspectionContentProps>(function SlatJointBarInspectionContent({
  data: order,
  readOnly = false,
  workItems,
  inspectionDataMap,
  inspectionSetting,
  schematicImage: schematicImageProp,
}, ref) {
  const schematicImage = inspectionSetting?.schematicImage || schematicImageProp;
  const fullDate = getFullDate();
  const today = getToday();
  const { documentNo, primaryAssignee } = getOrderInfo(order);

  const rowCount = workItems?.length || DEFAULT_ROW_COUNT;

  const [rows, setRows] = useState<InspectionRow[]>(() =>
    Array.from({ length: rowCount }, (_, i) => buildRow(i, workItems, inspectionDataMap))
  );

  const [inadequateContent, setInadequateContent] = useState('');

  useEffect(() => {
    const newRowCount = workItems?.length || DEFAULT_ROW_COUNT;
    setRows(Array.from({ length: newRowCount }, (_, i) => buildRow(i, workItems, inspectionDataMap)));
  }, [workItems, inspectionDataMap]);

  const handleStatusChange = useCallback((rowId: number, field: 'processStatus' | 'assemblyStatus', value: CheckStatus) => {
    if (readOnly) return;
    setRows(prev => prev.map(row =>
      row.id === rowId ? { ...row, [field]: value } : row
    ));
  }, [readOnly]);

  const handleInputChange = useCallback((rowId: number, field: keyof InspectionRow, value: string) => {
    if (readOnly) return;
    const filtered = value.replace(/[^\d.]/g, '');
    setRows(prev => prev.map(row =>
      row.id === rowId ? { ...row, [field]: filtered } : row
    ));
  }, [readOnly]);

  const getRowJudgment = useCallback((row: InspectionRow): '적' | '부' | null => {
    const { processStatus, assemblyStatus } = row;
    if (processStatus === '불량' || assemblyStatus === '불량') return '부';
    if (processStatus === '양호' && assemblyStatus === '양호') return '적';
    return null;
  }, []);

  const overallResult = useMemo(() => calculateOverallResult(rows.map(getRowJudgment)), [rows, getRowJudgment]);

  useImperativeHandle(ref, () => ({
    getInspectionData: () => ({
      rows: rows.map(row => ({
        id: row.id,
        processStatus: row.processStatus,
        assemblyStatus: row.assemblyStatus,
        height1Measured: row.height1Measured,
        height2Measured: row.height2Measured,
        lengthMeasured: row.lengthMeasured,
        intervalMeasured: row.intervalMeasured,
      })),
      inadequateContent,
      overallResult,
    }),
  }), [rows, inadequateContent, overallResult]);

  return (
    <InspectionLayout title="중간검사성적서 (조인트바)" documentNo={documentNo} fullDate={fullDate} primaryAssignee={primaryAssignee}>
      {/* ===== 기본 정보 ===== */}
      <table className="w-full border-collapse text-xs mb-6">
        <tbody>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium w-24">제품명</td>
            <td className="border border-gray-400 px-3 py-2">슬랫</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium w-28">제품 LOT NO</td>
            <td className="border border-gray-400 px-3 py-2">{order.lotNo || '-'}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">규격</td>
            <td className="border border-gray-400 px-3 py-2">슬랫</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">부서</td>
            <td className="border border-gray-400 px-3 py-2">{order.department || '생산부'}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">수주처</td>
            <td className="border border-gray-400 px-3 py-2">{order.client || '-'}</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">검사일자</td>
            <td className="border border-gray-400 px-3 py-2">{today}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">현장명</td>
            <td className="border border-gray-400 px-3 py-2">{order.projectName || '-'}</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">검사자</td>
            <td className="border border-gray-400 px-3 py-2">{primaryAssignee}</td>
          </tr>
        </tbody>
      </table>

      {/* ===== 중간검사 기준서 ===== */}
      <InspectionStandardSection inspectionSetting={inspectionSetting}>
      <table className="w-full border-collapse text-xs mb-6">
        <tbody>
          <tr>
            <td className="border border-gray-400 p-2 text-center align-middle w-1/4" rowSpan={8}>
              {schematicImage ? (
                <img src={schematicImage} alt="기준서 도해" className="max-h-40 mx-auto object-contain" />
              ) : (
                <div className="h-40 flex items-center justify-center text-gray-300">도해 이미지 영역</div>
              )}
            </td>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center" colSpan={2}>검사항목</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사기준</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사방법</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">검사주기</th>
            <th className="border border-gray-400 bg-gray-100 px-2 py-1 text-center">관련규정</th>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium text-center" rowSpan={3}>결모양</td>
            <td className="border border-gray-400 px-2 py-1 font-medium">가공상태</td>
            <td className="border border-gray-400 px-2 py-1">사용상 해로운 결함이 없을것</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={3}>육안검사</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={7}>n = 1, c = 0</td>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 5.1항</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium" rowSpan={2}>조립상태</td>
            <td className="border border-gray-400 px-2 py-1">엔드락이 용접에 의해<br/>견고하게 조립되어야 함</td>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 9항</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1">용접부위에 락카도색이<br/>되어야 함</td>
            <td className="border border-gray-400 px-2 py-1">자체규정</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium bg-gray-50 text-center" rowSpan={4}>치수<br/>(mm)</td>
            <td className="border border-gray-400 px-2 py-1 font-medium">① 높이</td>
            <td className="border border-gray-400 px-2 py-1 text-center">43.1 ± 0.5</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={4}>체크검사</td>
            <td className="border border-gray-400 px-2 py-1" rowSpan={3}>KS F 4510 7항<br/>표9</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium">② 높이</td>
            <td className="border border-gray-400 px-2 py-1 text-center">14.5 ± 1</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium">길이</td>
            <td className="border border-gray-400 px-2 py-1 text-center">도면치수 ± 4</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-2 py-1 font-medium">간격</td>
            <td className="border border-gray-400 px-2 py-1 text-center">150 ± 4</td>
            <td className="border border-gray-400 px-2 py-1">자체규정</td>
          </tr>
        </tbody>
      </table>
      </InspectionStandardSection>

      {/* ===== 중간검사 DATA ===== */}
      <div className="mb-1 font-bold text-sm">■ 중간검사 DATA</div>
      <table className="w-full border-collapse text-xs mb-4">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 p-1 w-8" rowSpan={2}>No.</th>
            <th className="border border-gray-400 p-1" colSpan={2}>겉모양</th>
            <th className="border border-gray-400 p-1" colSpan={2}>① 높이 (mm)</th>
            <th className="border border-gray-400 p-1" colSpan={2}>② 높이 (mm)</th>
            <th className="border border-gray-400 p-1" colSpan={2}>③ 길이 (mm)</th>
            <th className="border border-gray-400 p-1" colSpan={2}>④ 간격</th>
            <th className="border border-gray-400 p-1 w-14" rowSpan={2}>판정<br/>(적/부)</th>
          </tr>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 p-1 w-16">가공상태</th>
            <th className="border border-gray-400 p-1 w-16">조립상태</th>
            <th className="border border-gray-400 p-1 w-16">기준치</th>
            <th className="border border-gray-400 p-1 w-16">측정값</th>
            <th className="border border-gray-400 p-1 w-16">기준치</th>
            <th className="border border-gray-400 p-1 w-16">측정값</th>
            <th className="border border-gray-400 p-1 w-16">기준치</th>
            <th className="border border-gray-400 p-1 w-16">측정값</th>
            <th className="border border-gray-400 p-1 w-16">기준치</th>
            <th className="border border-gray-400 p-1 w-16">측정값</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => {
            const judgment = getRowJudgment(row);
            return (
              <tr key={row.id}>
                <td className="border border-gray-400 p-1 text-center">{row.id}</td>
                <CheckStatusCell value={row.processStatus} onToggle={(v) => handleStatusChange(row.id, 'processStatus', v)} readOnly={readOnly} />
                <CheckStatusCell value={row.assemblyStatus} onToggle={(v) => handleStatusChange(row.id, 'assemblyStatus', v)} readOnly={readOnly} />
                <td className="border border-gray-400 p-1 text-center">{row.height1Standard}</td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={row.height1Measured} onChange={(e) => handleInputChange(row.id, 'height1Measured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                <td className="border border-gray-400 p-1 text-center">{row.height2Standard}</td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={row.height2Measured} onChange={(e) => handleInputChange(row.id, 'height2Measured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                <td className="border border-gray-400 p-1 text-center">{row.lengthDesign || '-'}</td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={row.lengthMeasured} onChange={(e) => handleInputChange(row.id, 'lengthMeasured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                <td className="border border-gray-400 p-1 text-center">{row.intervalStandard}</td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={row.intervalMeasured} onChange={(e) => handleInputChange(row.id, 'intervalMeasured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                <JudgmentCell judgment={judgment} />
              </tr>
            );
          })}
        </tbody>
      </table>

      {/* ===== 부적합 내용 + 종합판정 ===== */}
      <InspectionFooter
        readOnly={readOnly}
        overallResult={overallResult}
        inadequateContent={inadequateContent}
        onInadequateContentChange={setInadequateContent}
      />
    </InspectionLayout>
  );
});