"use client";

/**
 * 발주서 문서 컴포넌트
 * - DocumentWrapper + DocumentTable building block 활용
 */

import { getTodayString } from "@/lib/utils/date";
import { OrderItem } from "../actions";
import { formatNumber } from '@/lib/utils/amount';
import { DocumentWrapper, DocumentTable, DOC_STYLES } from '@/components/document-system';

/**
 * 수량 포맷 함수
 * - EA, SET, PCS 등 개수 단위: 정수로 표시
 * - M, M2, KG, L 등 측정 단위: 소수점 이하 불필요한 0 제거
 */
function formatQuantity(quantity: number, unit?: string): string {
  const countableUnits = ["EA", "SET", "PCS", "개", "세트", "BOX", "ROLL"];
  const upperUnit = (unit || "").toUpperCase();

  if (countableUnits.includes(upperUnit)) {
    return formatNumber(Math.round(quantity));
  }

  const rounded = Math.round(quantity * 10000) / 10000;
  return rounded.toLocaleString(undefined, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 4
  });
}

interface PurchaseOrderDocumentProps {
  orderNumber: string;
  client: string;
  siteName?: string;
  manager?: string;
  managerContact?: string;
  deliveryRequestDate?: string;
  expectedShipDate?: string;
  deliveryMethod?: string;
  address?: string;
  orderDate?: string;
  installationCount?: number;
  items?: OrderItem[];
  remarks?: string;
}

export function PurchaseOrderDocument({
  orderNumber,
  client,
  siteName = "-",
  manager = "-",
  managerContact = "010-0123-4567",
  deliveryRequestDate = "-",
  expectedShipDate = "-",
  deliveryMethod = "상차",
  address = "-",
  orderDate = getTodayString(),
  installationCount = 3,
  items = [],
  remarks,
}: PurchaseOrderDocumentProps) {
  return (
    <DocumentWrapper fontSize="text-sm">
      {/* 헤더: 제목 + 로트번호/결재란 */}
      <div className="flex justify-between items-start mb-6">
        <h1 className="text-2xl font-bold tracking-widest">발 주 서</h1>
        <div className="text-right">
          <div className="flex items-center justify-end gap-2 mb-2 text-sm">
            <span className="text-gray-600">로트번호</span>
            <span className="font-medium">{orderNumber}</span>
          </div>
          <table className="border border-gray-300 text-xs">
            <thead>
              <tr className="bg-gray-100">
                <th className="border-r border-gray-300 px-2 py-1">결재</th>
                <th className="border-r border-gray-300 px-2 py-1">작성</th>
                <th className="border-r border-gray-300 px-2 py-1">검토</th>
                <th className="border-r border-gray-300 px-2 py-1">승인</th>
                <th className="border-r border-gray-300 px-2 py-1">전결</th>
                <th className="border-r border-gray-300 px-2 py-1">회계</th>
                <th className="px-2 py-1">생산</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td className="border-r border-t border-gray-300 h-8 w-10"></td>
                <td className="border-r border-t border-gray-300 h-8 w-10"></td>
                <td className="border-r border-t border-gray-300 h-8 w-10"></td>
                <td className="border-r border-t border-gray-300 h-8 w-10"></td>
                <td className="border-r border-t border-gray-300 h-8 w-10"></td>
                <td className="border-r border-t border-gray-300 h-8 w-10"></td>
                <td className="border-t border-gray-300 h-8 w-10"></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* 신청업체 */}
      <DocumentTable spacing="mb-4" className="text-sm">
        <tbody>
          <tr>
            <td rowSpan={2} className={`${DOC_STYLES.label} text-center w-20`}>
              신청업체
            </td>
            <td className={`${DOC_STYLES.label} w-20`}>발주처</td>
            <td className={DOC_STYLES.value}>{client}</td>
            <td className={`${DOC_STYLES.label} w-20`}>발주일</td>
            <td className={DOC_STYLES.value}>{orderDate}</td>
          </tr>
          <tr>
            <td className={`${DOC_STYLES.label} w-20`}>담당자</td>
            <td className={DOC_STYLES.value}>{manager}</td>
            <td className={`${DOC_STYLES.label} w-20`}>연락처</td>
            <td className={DOC_STYLES.value}>{managerContact}</td>
          </tr>
          <tr>
            <td className={`${DOC_STYLES.label} text-center w-20`}></td>
            <td className={`${DOC_STYLES.label} w-20`}>FAX</td>
            <td className={DOC_STYLES.value}>-</td>
            <td className={`${DOC_STYLES.label} w-20`}>설치개소<br/>(동)</td>
            <td className={DOC_STYLES.value}>{installationCount}개소</td>
          </tr>
        </tbody>
      </DocumentTable>

      {/* 신청내용 */}
      <DocumentTable spacing="mb-4" className="text-sm">
        <tbody>
          <tr>
            <td rowSpan={3} className={`${DOC_STYLES.label} text-center w-20`}>
              신청내용
            </td>
            <td className={`${DOC_STYLES.label} w-20`}>현장명</td>
            <td colSpan={3} className={DOC_STYLES.value}>{siteName}</td>
          </tr>
          <tr>
            <td className={`${DOC_STYLES.label} w-20`}>납기요청<br/>일</td>
            <td className={DOC_STYLES.value}>{deliveryRequestDate}</td>
            <td className={`${DOC_STYLES.label} w-20`}>배송방법</td>
            <td className={DOC_STYLES.value}>{deliveryMethod}</td>
          </tr>
          <tr>
            <td className={`${DOC_STYLES.label} w-20`}>출고일</td>
            <td className={DOC_STYLES.value}>{expectedShipDate}</td>
            <td className={`${DOC_STYLES.label} w-20`}>납품주소</td>
            <td className={DOC_STYLES.value}>{address}</td>
          </tr>
        </tbody>
      </DocumentTable>

      {/* 부자재 */}
      <div className="mb-4">
        <p className="text-sm font-medium mb-2">■ 부자재</p>
        <DocumentTable spacing="">
          <thead>
            <tr>
              <th className={`${DOC_STYLES.th} w-16`}>구분</th>
              <th className={`${DOC_STYLES.th} text-left`}>품명</th>
              <th className={`${DOC_STYLES.th} w-20`}>규격</th>
              <th className={`${DOC_STYLES.th} w-24`}>길이(mm)</th>
              <th className={`${DOC_STYLES.th} w-16`}>수량</th>
              <th className={`${DOC_STYLES.th} w-24`}>비고</th>
            </tr>
          </thead>
          <tbody>
            {items.length > 0 ? (
              items.map((item, index) => (
                <tr key={item.id}>
                  <td className={DOC_STYLES.tdCenter}>{index + 1}</td>
                  <td className={DOC_STYLES.td}>{item.itemName}</td>
                  <td className={DOC_STYLES.tdCenter}>{item.spec}</td>
                  <td className={DOC_STYLES.tdCenter}>
                    {item.width ? `${item.width}` : "-"}
                  </td>
                  <td className={DOC_STYLES.tdCenter}>{formatQuantity(item.quantity, item.unit)}</td>
                  <td className={DOC_STYLES.tdCenter}>{item.symbol || "-"}</td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={6} className="p-4 text-center text-gray-400 border border-gray-300">
                  등록된 품목이 없습니다
                </td>
              </tr>
            )}
          </tbody>
        </DocumentTable>
      </div>

      {/* 특이사항 */}
      <div className="mb-4">
        <p className="text-sm font-medium mb-2">【 특이사항 】</p>
        <div className="border border-gray-300 p-3 min-h-[50px] text-sm">
          {remarks || "-"}
        </div>
      </div>

      {/* 유의사항 */}
      <div className="mb-4">
        <p className="text-sm font-medium mb-2">【 유의사항 】</p>
        <div className="border border-gray-300 p-3 text-sm">
          <ul className="space-y-1">
            <li>• 발주 승인 완료 후 작업을 진행해주시기 바랍니다.</li>
            <li>• 납기 일정 부득이하게 변경이 필요할 경우 사전에 납품해주시기 바랍니다.</li>
            <li>• 기타 문의사항은 담당자에게 연락 부탁드립니다.</li>
          </ul>
        </div>
      </div>

      {/* 문의 */}
      <div className="text-center text-sm text-gray-600">
        문의: 홍길동 | 010-1234-5678
      </div>
    </DocumentWrapper>
  );
}
