'use client';

/**
 * 절곡 작업일지 문서 콘텐츠
 *
 * PHP viewBendingWork_slat.php와 동일한 구조로 완전 재구현
 *
 * 구성:
 * - 헤더: "작업일지 (절곡)" + 문서번호/작성일자 + 결재란
 * - 신청업체/신청내용 테이블
 * - 제품 정보 테이블 (제품명/재질/마감/유형)
 * - 4개 카테고리 섹션:
 *   1. 가이드레일 (벽면형/측면형)
 *   2. 하단마감재
 *   3. 셔터박스 (방향별)
 *   4. 연기차단재 (W50/W80)
 * - 생산량 합계 [kg] SUS/EGI
 */

import { useMemo } from 'react';
import type { WorkOrder } from '../types';
import type { BendingInfoExtended } from './bending/types';
import { ConstructionApprovalTable } from '@/components/document-system';
import { getMaterialMapping, calculateProductionSummary } from './bending/utils';
import { GuideRailSection } from './bending/GuideRailSection';
import { BottomBarSection } from './bending/BottomBarSection';
import { ShutterBoxSection } from './bending/ShutterBoxSection';
import { SmokeBarrierSection } from './bending/SmokeBarrierSection';
import { ProductionSummarySection } from './bending/ProductionSummarySection';

interface BendingWorkLogContentProps {
  data: WorkOrder;
  lotNoMap?: Record<string, string>;  // BD-{prefix}-{lengthCode} → LOT NO
  bendingImages?: Record<string, string>;  // R2 presigned URL 맵
  rawMaterialLotNo?: string;  // STOCK: 원자재 투입 LOT 번호
  isWip?: boolean;  // 재공품 여부 (수주 관련 필드 숨김)
}

export function BendingWorkLogContent({ data: order, lotNoMap, bendingImages, rawMaterialLotNo, isWip }: BendingWorkLogContentProps) {
  const today = new Date().toLocaleDateString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).replace(/\. /g, '-').replace('.', '');

  const fullDate = new Date().toLocaleDateString('ko-KR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });

  const documentNo = order.workOrderNo || 'ABC123';
  const primaryAssignee = order.assignees?.find(a => a.isPrimary)?.name || order.assignee || '-';
  const _items = order.items || [];

  const formattedDueDate = order.dueDate !== '-'
    ? new Date(order.dueDate).toLocaleDateString('ko-KR', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      }).replace(/\. /g, '-').replace('.', '')
    : '-';

  // 작업지시 레벨의 bendingInfo에서 절곡 데이터 추출
  const bendingInfo = order.bendingInfo as BendingInfoExtended | undefined;

  // bendingInfo가 없으면 빈 상태 표시
  const hasBendingData = !!bendingInfo?.productCode;

  // 재질 매핑
  const mapping = hasBendingData
    ? getMaterialMapping(bendingInfo!.productCode, bendingInfo!.finishMaterial)
    : null;

  // 생산량 합계
  const summary = hasBendingData && mapping
    ? calculateProductionSummary(bendingInfo!, mapping)
    : { susTotal: 0, egiTotal: 0, grandTotal: 0 };

  // STOCK 단일부품: 원자재 LOT를 모든 부품에 적용
  const effectiveLotNoMap = useMemo(() => {
    if (!rawMaterialLotNo || !bendingInfo?.isStockProduction) return lotNoMap;
    const map = { ...lotNoMap };
    // stockPartFilter의 각 부품에 원자재 LOT 번호 매핑
    const stockFilter = bendingInfo.stockPartFilter;
    if (stockFilter) {
      for (const part of stockFilter) {
        // partKey별 lotPrefix 매핑
        const prefixMap: Record<string, string[]> = {
          '본체': ['ST', 'SM', 'RT', 'RM'],
          'C형': ['SC', 'RC'],
          'D형': ['SD', 'RD'],
          '마감재': ['SS', 'SE', 'RS', 'RE'],
          '별도마감': ['YY'],
          'BASE': ['XX'],
        };
        const prefixes = prefixMap[part.partKey] || [];
        for (const prefix of prefixes) {
          // 와일드카드: BD-{prefix}-* 형태로 모든 길이에 매핑
          map[`BD-${prefix}-*`] = rawMaterialLotNo;
        }
      }
    }
    // 와일드카드 없이도 fallback으로 작동하도록 _raw 키 추가
    map['_rawMaterialLot'] = rawMaterialLotNo;
    return map;
  }, [lotNoMap, rawMaterialLotNo, bendingInfo]);

  return (
    <div className="p-6 bg-white">
      {/* ===== 헤더 영역 ===== */}
      <div className="flex justify-between items-start mb-6">
        <div>
          <h1 className="text-2xl font-bold">작업일지 (절곡)</h1>
          <p className="text-xs text-gray-500 mt-1 whitespace-nowrap">
            문서번호: {documentNo} | 작성일자: {fullDate}
          </p>
        </div>
        <ConstructionApprovalTable
          approvers={{ writer: { name: primaryAssignee } }}
          className="flex-shrink-0"
        />
      </div>

      {/* ===== 신청업체 / 신청내용 ===== */}
      <table className="w-full border-collapse text-xs mb-6">
        <thead>
          <tr>
            {!isWip && <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-center" colSpan={2}>신청업체</th>}
            <th className="border border-gray-400 bg-gray-100 px-3 py-2 text-center" colSpan={2}>
              {isWip ? '생산정보' : '신청내용'}
            </th>
          </tr>
        </thead>
        <tbody>
          {!isWip && (
            <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.salesOrderDate || '-'}</td>
              <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.projectName}</td>
            </tr>
          )}
          {!isWip && (
            <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>
          )}
          {isWip && (
            <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">{today}</td>
            </tr>
          )}
          <tr>
            {!isWip && (
              <>
                <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.salesOrderWriter || '-'}</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.lotNo}</td>
          </tr>
          <tr>
            {!isWip && (
              <>
                <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.clientContact || '-'}</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>
          {!isWip && (
            <tr>
              <td className="border border-gray-400 bg-gray-50 px-3 py-2 font-medium" colSpan={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">{formattedDueDate}</td>
            </tr>
          )}
        </tbody>
      </table>

      {/* ===== 제품 정보 ===== */}
      <table className="w-full border-collapse text-xs mb-6">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 p-2">제품명</th>
            <th className="border border-gray-400 p-2">재질</th>
            <th className="border border-gray-400 p-2">마감</th>
            <th className="border border-gray-400 p-2">유형</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td className="border border-gray-400 p-2">
              {hasBendingData ? bendingInfo!.productCode : '-'}
            </td>
            <td className="border border-gray-400 p-2">
              {mapping?.bodyMaterial || '-'}
            </td>
            <td className="border border-gray-400 p-2">
              {hasBendingData ? bendingInfo!.finishMaterial : '-'}
            </td>
            <td className="border border-gray-400 p-2">
              {hasBendingData ? bendingInfo!.common.type : '-'}
            </td>
          </tr>
        </tbody>
      </table>

      {/* ===== 4개 카테고리 섹션 ===== */}
      {hasBendingData && mapping ? (
        <>
          <GuideRailSection
            bendingInfo={bendingInfo!}
            mapping={mapping}
            lotNo={order.lotNo}
            lotNoMap={effectiveLotNoMap}
            bendingImages={bendingImages}
          />
          <BottomBarSection
            bendingInfo={bendingInfo!}
            mapping={mapping}
            lotNoMap={effectiveLotNoMap}
            bendingImages={bendingImages}
          />
          <ShutterBoxSection
            bendingInfo={bendingInfo!}
            lotNoMap={effectiveLotNoMap}
            bendingImages={bendingImages}
          />
          <SmokeBarrierSection
            bendingInfo={bendingInfo!}
            lotNoMap={effectiveLotNoMap}
            bendingImages={bendingImages}
          />
        </>
      ) : (
        <div className="text-center text-gray-400 text-sm py-8 border border-gray-300 mb-6">
          절곡 데이터가 없습니다. (bending_info 미등록)
        </div>
      )}

      {/* ===== 생산량 합계 ===== */}
      <ProductionSummarySection summary={summary} />

      {/* ===== 비고 ===== */}
      <table className="w-full border-collapse text-xs">
        <tbody>
          <tr>
            <td className="border border-gray-400 bg-gray-100 px-3 py-2 font-medium w-40 align-top">비고</td>
            <td className="border border-gray-400 px-3 py-3 min-h-[60px]">
              {order.note || ''}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}
