'use client';

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

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
}

export function BendingWorkLogContent({ data: order, lotNoMap }: 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 };

  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>
            <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}>신청내용</th>
          </tr>
        </thead>
        <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.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>
          <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.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>
            <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>
          <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={lotNoMap}
          />
          <BottomBarSection
            bendingInfo={bendingInfo!}
            mapping={mapping}
            lotNoMap={lotNoMap}
          />
          <ShutterBoxSection
            bendingInfo={bendingInfo!}
            lotNoMap={lotNoMap}
          />
          <SmokeBarrierSection
            bendingInfo={bendingInfo!}
            lotNoMap={lotNoMap}
          />
        </>
      ) : (
        <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>
  );
}
