'use client';

/**
 * 슬랫 작업일지 문서 콘텐츠
 *
 * 기획서 기준 구성:
 * - 헤더: "작업일지 (슬랫)" + 문서번호/작성일자 + 결재란(결재|작성/승인/승인/승인)
 * - 신청업체(수주일,수주처,담당자,연락처) / 신청내용(현장명,작업일자,제품LOT NO,생산담당자,출고예정일)
 * - 작업내역: No, 입고 LOT NO, 방화유리 수량, 제품명,
 *   제작사이즈(mm)-미미제외(가로/세로/매수(세로)), 조인트바 수량, 코일 사용량, 설치홈/부호
 * - 생산량 합계[m²] / 조인트바 합계
 * - 비고
 */

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

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

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

export function SlatWorkLogContent({ data: order, materialLots: _materialLots = [] }: SlatWorkLogContentProps) {
  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) : '-';

  // 소수점: 정수면 소수점 없이, 소수면 소수점 1자리까지
  const fmtDec = (v: number) => Number.isInteger(v) ? String(v) : v.toFixed(1);

  // 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('.', '')
    : '-';

  // 슬랫 계산: 매수(세로) = floor(height / 72) + 1
  const calcSlatCount = (height?: number) => height ? Math.floor(height / 72) + 1 : 0;

  // 코일 사용량 = ((가로 + 4) × 매수) / 1000 + (304 × 3 × 조인트바) / 1000
  const calcCoilUsage = (width?: number, height?: number, jointBar?: number) => {
    const slatCount = calcSlatCount(height);
    const w = width || 0;
    const jb = jointBar || 0;
    return Math.round(((w + 4) * slatCount / 1000 + (304 * 3 * jb) / 1000) * 10) / 10;
  };

  // 합계 계산
  let totalCoilUsage = 0;
  let totalJointBar = 0;
  items.forEach(item => {
    const jb = item.slatInfo?.jointBar || 0;
    totalJointBar += jb;
    totalCoilUsage += calcCoilUsage(item.width, item.height, jb);
  });

  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>

        {/* 우측: 결재란 */}
        <table className="border-collapse text-sm flex-shrink-0">
          <tbody>
            <tr>
              <td className="border border-gray-400 px-4 py-1 text-center align-middle" rowSpan={3}>결<br/>재</td>
              <td className="border border-gray-400 px-6 py-1 text-center">작성</td>
              <td className="border border-gray-400 px-6 py-1 text-center">승인</td>
              <td className="border border-gray-400 px-6 py-1 text-center">승인</td>
              <td className="border border-gray-400 px-6 py-1 text-center">승인</td>
            </tr>
            <tr>
              <td className="border border-gray-400 px-6 py-3 text-center">{primaryAssignee}</td>
              <td className="border border-gray-400 px-6 py-3 text-center text-gray-400">이름</td>
              <td className="border border-gray-400 px-6 py-3 text-center text-gray-400">이름</td>
              <td className="border border-gray-400 px-6 py-3 text-center text-gray-400">이름</td>
            </tr>
            <tr>
              <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
              <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
              <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
              <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
            </tr>
          </tbody>
        </table>
      </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 border-collapse text-xs mb-6">
        <thead>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 px-2 py-1 w-7" rowSpan={2}>No.</th>
            <th className="border border-gray-400 px-2 py-1" rowSpan={2}>입고 LOT<br/>NO</th>
            <th className="border border-gray-400 px-2 py-1 whitespace-nowrap" rowSpan={2}>방화유리<br/>수량</th>
            <th className="border border-gray-400 px-2 py-1" rowSpan={2}>제품명</th>
            <th className="border border-gray-400 px-2 py-1" colSpan={3}>제작사이즈(mm) - 미미제외</th>
            <th className="border border-gray-400 px-2 py-1 whitespace-nowrap" rowSpan={2}>조인트바<br/>수량</th>
            <th className="border border-gray-400 px-2 py-1 whitespace-nowrap" rowSpan={2}>코일<br/>사용량</th>
            <th className="border border-gray-400 px-2 py-1 whitespace-nowrap" rowSpan={2}>층/<br/>부호</th>
          </tr>
          <tr className="bg-gray-100">
            <th className="border border-gray-400 px-2 py-1">가로</th>
            <th className="border border-gray-400 px-2 py-1">세로</th>
            <th className="border border-gray-400 px-2 py-1 whitespace-nowrap">매수<br/>(세로)</th>
          </tr>
        </thead>
        <tbody>
          {items.length > 0 ? (
            items.map((item, idx) => {
              const slatCount = calcSlatCount(item.height);
              const jointBar = item.slatInfo?.jointBar || 0;
              const glassQty = item.slatInfo?.glassQty || 0;
              const coilUsage = calcCoilUsage(item.width, item.height, jointBar);
              return (
                <tr key={item.id}>
                  <td className="border border-gray-400 px-2 py-1 text-center">{idx + 1}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{item.materialInputLots?.join(', ') || ''}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{glassQty > 0 ? fmt(glassQty) : '-'}</td>
                  <td className="border border-gray-400 px-2 py-1">{item.productName}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center whitespace-nowrap">{fmt(item.width)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center whitespace-nowrap">{fmt(item.height)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{slatCount > 0 ? fmt(slatCount) : '-'}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{jointBar > 0 ? fmt(jointBar) : '-'}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{coilUsage > 0 ? fmtDec(coilUsage) : '-'}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center whitespace-nowrap">{getSymbolCode(item.floorCode)}</td>
                </tr>
              );
            })
          ) : (
            <tr>
              <td colSpan={10} className="border border-gray-400 px-2 py-4 text-center text-gray-400">
                등록된 품목이 없습니다.
              </td>
            </tr>
          )}
        </tbody>
      </table>

      {/* ===== 생산량 합계 / 조인트바 합계 ===== */}
      <table className="w-full border-collapse text-xs mb-6">
        <tbody>
          <tr>
            <td className="border border-gray-400 bg-gray-100 px-3 py-2 font-medium whitespace-nowrap">생산량 합계 [m²]</td>
            <td className="border border-gray-400 px-3 py-2">{totalCoilUsage > 0 ? fmtDec(totalCoilUsage) : ''}</td>
            <td className="border border-gray-400 bg-gray-100 px-3 py-2 font-medium whitespace-nowrap">조인트바 합계</td>
            <td className="border border-gray-400 px-3 py-2">{totalJointBar > 0 ? fmt(totalJointBar) : ''}</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>
  );
}
