'use client';

/**
 * 스크린 작업일지 문서 콘텐츠
 *
 * 기존 시스템(5130/output/viewScreenWork.php) 기준 구성:
 * - 헤더: "작업일지 (스크린)" + 문서번호/작성일자 + 결재란(작성/검토/승인)
 * - 신청업체(수주일,수주처,담당자,연락처) / 신청내용(현장명,작업일자,제품LOT NO,생산담당자,출고예정일)
 * - 작업내역 테이블: No, 입고 LOT NO, 제품명, 부호, 제작사이즈(가로/세로), 나머지 높이,
 *   규격(매수) 6열({기준폭}/900/800/600/400/300)
 * - 합계
 * - 내화실 입고 LOT NO
 * - 비고
 *
 * 계산 로직 (5130/output/common/function.php calculateCutSize):
 * 1. 기준폭: 실리카=1220, 와이어=1180, 화이바=1200
 * 2. 시접: makeVertical = height + 140 + floor(height/기준폭) * 40
 * 3. 절단매수(firstCut) = floor(makeVertical / 기준폭)
 * 4. 나머지높이 = makeVertical - (firstCut * 기준폭)
 * 5. 나머지 > 임계치 → firstCut++
 * 6. 나머지높이로 규격 분류 (범위별 0 or 1)
 */

import type { WorkOrder, WorkOrderItem } from '../types';
import { SectionHeader, ConstructionApprovalTable } from '@/components/document-system';
import { formatNumber } from '@/lib/utils/amount';

// ===== 절단 계산 로직 (기존 시스템 calculateCutSize 이식) =====

type FabricType = '실리카' | '와이어' | '화이바';

interface FabricConfig {
  width: number;      // 기준폭 (mm)
  threshold: number;  // 추가 절단 임계치
  ranges: Record<string, [number, number]>;  // 규격별 분류 범위 [min, max]
}

const FABRIC_CONFIG: Record<FabricType, FabricConfig> = {
  '실리카': {
    width: 1220, threshold: 940,
    ranges: { '900': [841, 940], '800': [641, 840], '600': [441, 640], '400': [341, 440], '300': [1, 340] },
  },
  '와이어': {
    width: 1180, threshold: 900,
    ranges: { '900': [801, 900], '800': [601, 800], '600': [401, 600], '400': [301, 400], '300': [1, 300] },
  },
  '화이바': {
    width: 1200, threshold: 924,
    ranges: { '900': [825, 924], '800': [625, 824], '600': [425, 624], '400': [325, 424], '300': [1, 324] },
  },
};

interface CutResult {
  firstCut: number;   // 기준폭 매수
  remaining: number;  // 나머지 높이
  sizes: Record<string, number>;  // { '900': 0|1, '800': 0|1, ... }
}

function detectFabricType(productName: string): FabricType {
  if (productName.includes('실리')) return '실리카';
  if (productName.includes('화이')) return '화이바';
  return '와이어'; // 기본값
}

function calculateCutSize(fabricType: FabricType, height: number): CutResult {
  const cfg = FABRIC_CONFIG[fabricType];
  const { width, threshold, ranges } = cfg;

  // 시접 계산
  const makeVertical = height + 140 + Math.floor(height / width) * 40;

  // 기본 절단 횟수
  let firstCut = Math.floor(makeVertical / width);

  // 나머지 높이
  const remaining = makeVertical - (firstCut * width);

  // 임계치 초과 시 추가 절단
  if (remaining > threshold) {
    firstCut++;
  }

  // 규격별 분류
  const sizes: Record<string, number> = {};
  for (const [key, [min, max]] of Object.entries(ranges)) {
    sizes[key] = (remaining >= min && remaining <= max) ? 1 : 0;
  }

  return { firstCut, remaining, sizes };
}

// ===== 컴포넌트 =====

interface MaterialInputLot {
  lot_no: string;
  item_code: string;
  item_name: string;
  total_qty: number;
  input_count: number;
  first_input_at: string;
}

interface ScreenWorkLogContentProps {
  data: WorkOrder;
  materialLots?: MaterialInputLot[];
}

export function ScreenWorkLogContent({ data: order, materialLots = [] }: ScreenWorkLogContentProps) {
  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 fmt = (v?: number) => v != null ? formatNumber(v) : '-';

  // floorCode에서 부호 추출: "1층/FSS-01" → "FSS-01"
  const getSymbolCode = (floorCode?: string) => {
    if (!floorCode || floorCode === '-') return '-';
    const parts = floorCode.split('/');
    return parts.length > 1 ? parts.slice(1).join('/') : floorCode;
  };

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

  // 원단 유형 판별 (첫 번째 아이템 기준)
  const fabricType = items.length > 0 ? detectFabricType(items[0].productName) : '와이어';
  const baseWidth = FABRIC_CONFIG[fabricType].width;

  // 규격 사이즈 헤더 (기준폭 + 900/800/600/400/300)
  const SPEC_SIZES = [String(baseWidth), '900', '800', '600', '400', '300'];

  // 각 아이템별 절단 계산
  const itemCuts = items.map((item: WorkOrderItem) => {
    if (!item.height || item.height <= 0) return null;
    const ft = detectFabricType(item.productName);
    return calculateCutSize(ft, item.height);
  });

  // 합계 계산
  const totals = SPEC_SIZES.reduce<Record<string, number>>((acc, size) => {
    acc[size] = 0;
    return acc;
  }, {});

  itemCuts.forEach((cut) => {
    if (!cut) return;
    totals[String(baseWidth)] += cut.firstCut;
    for (const key of ['900', '800', '600', '400', '300']) {
      totals[key] += cut.sizes[key] || 0;
    }
  });

  // 투입 LOT 번호 (중복 제거)
  const lotNoList = materialLots.map(lot => lot.lot_no).filter(Boolean);
  const lotNoDisplay = lotNoList.length > 0 ? lotNoList.join(', ') : '';

  // 투입 자재 LOT 그룹핑 (item_name별) — 하단 자재별 LOT 섹션용
  const materialLotGroupMap = new Map<string, string[]>();
  materialLots.forEach(lot => {
    const name = lot.item_name || '기타';
    if (!materialLotGroupMap.has(name)) materialLotGroupMap.set(name, []);
    materialLotGroupMap.get(name)!.push(lot.lot_no);
  });
  const materialLotGroups = Array.from(materialLotGroupMap.entries()).map(([name, lots]) => ({
    itemName: name,
    lotNos: lots.filter(Boolean).join(', '),
  }));

  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>

      {/* ===== 작업내역 ===== */}
      <SectionHeader variant="dark">작업내역</SectionHeader>
      <table className="w-full table-fixed border-collapse text-xs mb-6">
        {/* No. | 입고 LOT NO | 제품명 | 부호 | 가로 | 세로 | 나머지높이 | 규격별 */}
        <colgroup><col style={{ width: '28px' }} /><col style={{ width: '72px' }} /><col style={{ width: '80px' }} /><col style={{ width: '60px' }} /><col style={{ width: '52px' }} /><col style={{ width: '52px' }} /><col style={{ width: '44px' }} />{SPEC_SIZES.map(s => <col key={s} style={{ width: '40px' }} />)}</colgroup>
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 p-1" rowSpan={2}>No.</th>
            <th className="border border-gray-400 p-1" rowSpan={2}>입고 LOT<br/>NO</th>
            <th className="border border-gray-400 p-1" rowSpan={2}>제품명</th>
            <th className="border border-gray-400 p-1" rowSpan={2}>부호</th>
            <th className="border border-gray-400 p-1" colSpan={2}>제작사이즈(mm)</th>
            <th className="border border-gray-400 p-1" rowSpan={2}>나머지<br/>높이</th>
            <th className="border border-gray-400 p-1" colSpan={6}>규격 (매수)</th>
          </tr>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 p-1">가로</th>
            <th className="border border-gray-400 p-1">세로</th>
            {SPEC_SIZES.map(size => (
              <th key={size} className="border border-gray-400 p-1">{size}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {items.length > 0 ? (
            items.map((item, idx) => {
              const cut = itemCuts[idx];
              return (
                <tr key={item.id}>
                  <td className="border border-gray-400 p-1 text-center">{idx + 1}</td>
                  <td className="border border-gray-400 p-1 text-center">{lotNoDisplay}</td>
                  <td className="border border-gray-400 p-1">{item.productName}</td>
                  <td className="border border-gray-400 p-1 text-center whitespace-nowrap">{getSymbolCode(item.floorCode)}</td>
                  <td className="border border-gray-400 p-1 text-center whitespace-nowrap font-bold text-red-600">{fmt(item.width)}</td>
                  <td className="border border-gray-400 p-1 text-center whitespace-nowrap font-bold text-red-600">{fmt(item.height)}</td>
                  <td className="border border-gray-400 p-1 text-center font-bold">{cut && cut.remaining > 0 ? cut.remaining : ''}</td>
                  <td className="border border-gray-400 p-1 text-center">{cut && cut.firstCut > 0 ? cut.firstCut : ''}</td>
                  {['900', '800', '600', '400', '300'].map(size => (
                    <td key={size} className="border border-gray-400 p-1 text-center">
                      {cut && cut.sizes[size] > 0 ? cut.sizes[size] : ''}
                    </td>
                  ))}
                </tr>
              );
            })
          ) : (
            <tr>
              <td colSpan={13} className="border border-gray-400 p-4 text-center text-gray-400">
                등록된 품목이 없습니다.
              </td>
            </tr>
          )}
          {/* 합계 행 */}
          <tr className="bg-orange-50 font-medium">
            <td className="border border-gray-400 p-1 text-center" colSpan={7}>합계</td>
            {SPEC_SIZES.map(size => (
              <td key={size} className="border border-gray-400 p-1 text-center font-bold">
                {totals[size] > 0 ? totals[size] : ''}
              </td>
            ))}
          </tr>
        </tbody>
      </table>

      {/* ===== 투입 자재 입고 LOT NO (자재별 동적 행) ===== */}
      <table className="w-full border-collapse text-xs mb-6">
        <tbody>
          {materialLotGroups.length > 0 ? (
            materialLotGroups.map((group, idx) => (
              <tr key={idx}>
                <td className="border border-gray-400 bg-yellow-50 px-3 py-2 font-bold w-40">
                  {group.itemName} 입고 LOT NO
                </td>
                <td className="border border-gray-400 px-3 py-2 min-h-[32px]">
                  {group.lotNos || '\u00A0'}
                </td>
              </tr>
            ))
          ) : (
            <tr>
              <td className="border border-gray-400 bg-yellow-50 px-3 py-2 font-bold w-40">
                자재 입고 LOT NO
              </td>
              <td className="border border-gray-400 px-3 py-2 min-h-[32px]">{'\u00A0'}</td>
            </tr>
          )}
        </tbody>
      </table>

      {/* ===== 비고 ===== */}
      <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>
  );
}
