'use client';

/**
 * 절곡 재공품 통합 문서 (작업일지 & 중간검사성적서)
 *
 * 기획서 기준:
 * - 제목: "절곡품 재고생산 작업일지 중간검사성적서"
 * - 결재란: 작성/승인/승인/승인
 * - 기본 정보: 제품명, 규격, 길이, 판고 LOT NO / 생산 LOT NO, 수량, 검사일자, 검사자
 * - ■ 중간검사 기준서 KDPS-20: 도해 IMG + 검사항목(겉모양/절곡상태, 치수/길이/폭/간격)
 * - ■ 중간검사 DATA: No, 제품명, 절곡상태(양호/불량), 길이(mm), 너비(mm)+포인트, 간격(mm), 판정
 * - 부적합 내용 / 종합판정 (자동)
 */

import { useState, useCallback, useMemo, forwardRef, useImperativeHandle, useEffect } from 'react';
import type { WorkOrder } from '../types';
import type { BendingInfoExtended } from './bending/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 BendingWipInspectionContentProps {
  data: WorkOrder;
  readOnly?: boolean;
  inspectionData?: InspectionData;
  workItems?: WorkItemData[];
  inspectionDataMap?: InspectionDataMap;
  inspectionSetting?: InspectionSetting;
  schematicImage?: string;
  inspectionStandardImage?: string;
}

interface InspectionRow {
  id: number;
  itemId?: string;
  partName: string;     // 검사부위: "가이드레일(측면) 본체(철재)"
  productName: string;
  processStatus: CheckStatus;
  lengthDesign: string;
  lengthMeasured: string;
  widthDesign: string;
  widthMeasured: string;
  spacingPoint: string;
  spacingDesign: string;
  spacingMeasured: string;
}

/** 품목명에서 길이(mm) 추출: "가이드레일(측면) 본체(철재) 2438mm" → "2438" */
function extractLengthFromItemName(name?: string): string {
  if (!name) return '-';
  const m = name.match(/(\d{3,5})\s*mm/i);
  return m ? m[1] : '-';
}

function buildRow(i: number, order: WorkOrder, workItems?: WorkItemData[], inspectionDataMap?: InspectionDataMap, bendingInfo?: BendingInfoExtended): InspectionRow {
  const item = workItems?.[i];
  const orderItem = order.items?.[i];
  const itemData = item && inspectionDataMap?.get(item.id);
  const itemName = item?.itemName || orderItem?.productName || '';

  // 실제 길이: 품목명에서 추출 → bendingInfo에서 추출 → 폴백
  let lengthDesign = extractLengthFromItemName(itemName);
  if (lengthDesign === '-' && bendingInfo?.guideRail) {
    const data = bendingInfo.guideRail.side || bendingInfo.guideRail.wall;
    const len = data?.lengthData?.[0]?.length;
    if (len) lengthDesign = String(len);
  }

  // 검사부위: 품목명에서 길이(mm) 부분 제거 → "가이드레일(측면) 본체(철재)"
  const partName = itemName.replace(/\s*\d{3,5}\s*mm\s*/i, '').trim();

  return {
    id: i + 1,
    itemId: item?.id,
    partName,
    productName: itemName,
    processStatus: itemData ? convertToCheckStatus(itemData.bendingStatus) : null,
    lengthDesign,
    lengthMeasured: '',
    widthDesign: 'N/A',
    widthMeasured: 'N/A',
    spacingPoint: '',
    spacingDesign: '-',
    spacingMeasured: '',
  };
}

export const BendingWipInspectionContent = forwardRef<InspectionContentRef, BendingWipInspectionContentProps>(function BendingWipInspectionContent({
  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 bendingInfo = order.bendingInfo as BendingInfoExtended | undefined;

  // 실제 품목 수만큼만 행 생성 (빈 행 제거)
  const actualItemCount = order.items?.filter(item => item.productName)?.length || 0;
  const rowCount = actualItemCount || 1;

  const [rows, setRows] = useState<InspectionRow[]>([]);
  const [inadequateContent, setInadequateContent] = useState('');

  useEffect(() => {
    const count = order.items?.filter(item => item.productName)?.length || 1;
    setRows(Array.from({ length: count }, (_, i) => buildRow(i, order, workItems, inspectionDataMap, bendingInfo)));
  }, [workItems, inspectionDataMap, order.items, bendingInfo?.productCode]);

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

  const handleInputChange = useCallback((rowId: number, field: keyof InspectionRow, value: string) => {
    if (readOnly) return;
    setRows(prev => prev.map(row =>
      row.id === rowId ? { ...row, [field]: value } : row
    ));
  }, [readOnly]);

  const handleNumericInput = 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 => {
    if (row.processStatus === '불량') return '부';
    if (row.processStatus === '양호') return '적';
    return null;
  }, []);

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

  useImperativeHandle(ref, () => ({
    getInspectionData: () => ({
      rows: rows.map(row => ({
        id: row.id,
        productName: row.productName,
        processStatus: row.processStatus,
        lengthMeasured: row.lengthMeasured,
        widthMeasured: row.widthMeasured,
        spacingPoint: row.spacingPoint,
        spacingMeasured: row.spacingMeasured,
      })),
      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">{order.items?.[0]?.productName || '가이드레일'}</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">{order.items?.[0]?.specification || 'EGI 1.6T'}</td>
            <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium">생산 LOT NO</td>
            <td className="border border-gray-400 px-3 py-2">{order.workOrderNo || '-'}</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">{(() => {
              const len = extractLengthFromItemName(order.items?.[0]?.productName);
              return len !== '-' ? `${Number(len).toLocaleString()} mm` : '-';
            })()}</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.items?.reduce((sum, item) => sum + item.quantity, 0) || 0} EA</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">{today}</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 table-fixed border-collapse text-xs mb-6">
        <colgroup>
          <col style={{width: '200px'}} />
          <col style={{width: '52px'}} />
          <col style={{width: '58px'}} />
          <col />
          <col style={{width: '68px'}} />
          <col style={{width: '78px'}} />
          <col style={{width: '120px'}} />
        </colgroup>
        <tbody>
          <tr>
            <td className="border border-gray-400 p-3 text-center align-middle" rowSpan={4}>
              <div className="text-xs font-medium text-gray-500 mb-2 text-left">도해</div>
              {schematicImage ? (
                <img src={schematicImage} alt="기준서 도해" className="max-h-32 mx-auto object-contain" />
              ) : (
                <div className="h-32 border border-gray-300 rounded flex items-center justify-center text-gray-300 text-sm">IMG</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">겉모양</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">육안검사</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={3}>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 bg-gray-50" rowSpan={2}>치수<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">도면치수 ± 4</td>
            <td className="border border-gray-400 px-2 py-1 text-center" rowSpan={2}>체크검사</td>
            <td className="border border-gray-400 px-2 py-1">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">도면치수 ± 2</td>
            <td className="border border-gray-400 px-2 py-1">KS F 4510 7항<br/>표9 / 자체규정</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" rowSpan={2}>검사 부위</th>
            <th className="border border-gray-400 p-1 w-16" rowSpan={2}>절곡상태<br/>겉모양</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={3}>간격 (mm)</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-14">도면치수</th>
            <th className="border border-gray-400 p-1 w-14">측정값</th>
            <th className="border border-gray-400 p-1 w-14">도면치수</th>
            <th className="border border-gray-400 p-1 w-14">측정값</th>
            <th className="border border-gray-400 p-1 w-12">포인트</th>
            <th className="border border-gray-400 p-1 w-14">도면치수</th>
            <th className="border border-gray-400 p-1 w-14">측정값</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>
                <td className="border border-gray-400 p-1">{row.partName || '-'}</td>
                <CheckStatusCell value={row.processStatus} onToggle={(v) => handleStatusChange(row.id, v)} readOnly={readOnly} />
                <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) => handleNumericInput(row.id, 'lengthMeasured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                <td className="border border-gray-400 p-1 text-center">{row.widthDesign}</td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={row.widthMeasured} onChange={(e) => handleInputChange(row.id, 'widthMeasured', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={row.spacingPoint} onChange={(e) => handleInputChange(row.id, 'spacingPoint', e.target.value)} disabled={readOnly} className={INPUT_CLASS} placeholder="-" />
                </td>
                <td className="border border-gray-400 p-1 text-center">{row.spacingDesign}</td>
                <td className="border border-gray-400 p-1">
                  <input type="text" value={row.spacingMeasured} onChange={(e) => handleNumericInput(row.id, 'spacingMeasured', 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>
  );
});