"use client";

/**
 * 계약서 문서 컴포넌트
 *
 * 공통 컴포넌트 사용:
 * - DocumentHeader: simple 레이아웃 (결재란 없음)
 */

import { formatAmount, formatNumber } from "@/lib/utils/amount";
import { OrderItem } from "../actions";
import { DocumentHeader } from "@/components/document-system";

/**
 * 수량 포맷 함수 (정수로 표시)
 */
function formatQuantity(quantity: number): string {
  return formatNumber(Math.round(quantity));
}

// 제품 정보 타입
interface ProductInfo {
  productName: string;
  productCategory?: string;
  openWidth?: string;
  openHeight?: string;
  quantity: number;
  floor?: string;
  code?: string;
}

interface ContractDocumentProps {
  orderNumber: string;
  orderDate: string;
  client: string;
  siteName?: string;
  clientManager?: string;
  clientContact?: string;
  companyName?: string;
  companyCeo?: string;
  companyBusinessNumber?: string;
  companyContact?: string;
  companyAddress?: string;
  items?: OrderItem[];
  products?: ProductInfo[];
  subtotal?: number;
  discountRate?: number;
  totalAmount?: number;
  remarks?: string;
}

export function ContractDocument({
  orderNumber,
  orderDate,
  client,
  siteName,
  clientManager,
  clientContact,
  companyName,
  companyCeo,
  companyBusinessNumber,
  companyContact,
  companyAddress,
  items: _items = [],
  products,
  subtotal = 0,
  discountRate = 0,
  totalAmount: _totalAmount = 0,
  remarks,
}: ContractDocumentProps) {
  const discountAmount = Math.round(subtotal * (discountRate / 100));
  const afterDiscount = subtotal - discountAmount;
  const vat = Math.round(afterDiscount * 0.1);
  const finalTotal = afterDiscount + vat;

  return (
    <div className="bg-white p-8 min-h-full">
      {/* 문서 헤더 (공통 컴포넌트) */}
      <DocumentHeader
        title="계 약 서"
        subtitle={`수주번호: ${orderNumber} | 계약일자: ${orderDate}`}
        layout="simple"
        approval={null}
        className="mb-6"
      />

      {/* 제품 정보 (개소별) */}
      <div className="border border-gray-300 mb-4">
        <div className="bg-gray-800 text-white p-2 text-sm font-medium text-center">
          수주 제품 (개소별 사이즈)
        </div>
        <div className="p-3">
          {products && products.length > 0 ? (
            <div className="space-y-3">
              {products.map((product, index) => (
                <div
                  key={index}
                  className="border border-gray-200 rounded p-3 bg-gray-50"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-xs font-medium text-gray-500 bg-white px-2 py-0.5 rounded border">
                      항목 {index + 1}
                    </span>
                    {product.floor && (
                      <span className="text-xs font-medium text-blue-600 bg-blue-50 px-2 py-0.5 rounded">
                        {product.floor}
                      </span>
                    )}
                  </div>

                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                    <div>
                      <span className="text-gray-500 text-xs">제품명</span>
                      <p className="font-medium">{product.productName}</p>
                    </div>
                    <div>
                      <span className="text-gray-500 text-xs">오픈사이즈</span>
                      <p className="font-medium">
                        {product.openWidth && product.openHeight
                          ? `${product.openWidth} × ${product.openHeight} mm`
                          : "-"}
                      </p>
                    </div>
                    <div>
                      <span className="text-gray-500 text-xs">수량</span>
                      <p className="font-medium">{formatQuantity(product.quantity)} SET</p>
                    </div>
                    {product.code && (
                      <div>
                        <span className="text-gray-500 text-xs">부호</span>
                        <p className="font-medium">{product.code}</p>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-center text-gray-400 py-4">
              등록된 제품이 없습니다
            </p>
          )}
        </div>
      </div>

      {/* 발주처/당사 정보 */}
      <div className="grid grid-cols-2 gap-4 mb-4">
        <div className="border border-gray-300">
          <div className="bg-gray-800 text-white p-2 text-sm font-medium text-center">
            발주처정보
          </div>
          <div className="p-3 space-y-1 text-sm">
            <div className="flex">
              <span className="w-20 text-gray-600">업체명</span>
              <span>{client || "-"}</span>
            </div>
            <div className="flex">
              <span className="w-20 text-gray-600">현장명</span>
              <span>{siteName || "-"}</span>
            </div>
            <div className="flex">
              <span className="w-20 text-gray-600">담당자</span>
              <span>{clientManager || "-"}</span>
            </div>
            <div className="flex">
              <span className="w-20 text-gray-600">연락처</span>
              <span>{clientContact || "-"}</span>
            </div>
          </div>
        </div>
        <div className="border border-gray-300">
          <div className="bg-gray-800 text-white p-2 text-sm font-medium text-center">
            당사정보
          </div>
          <div className="p-3 space-y-1 text-sm">
            <div className="flex">
              <span className="w-20 text-gray-600">업체명</span>
              <span>{companyName || "-"}</span>
            </div>
            <div className="flex">
              <span className="w-20 text-gray-600">대표자</span>
              <span>{companyCeo || "-"}</span>
            </div>
            <div className="flex">
              <span className="w-20 text-gray-600">사업자번호</span>
              <span>{companyBusinessNumber || "-"}</span>
            </div>
            <div className="flex">
              <span className="w-20 text-gray-600">연락처</span>
              <span>{companyContact || "-"}</span>
            </div>
            <div className="flex">
              <span className="w-20 text-gray-600">주소</span>
              <span>{companyAddress || "-"}</span>
            </div>
          </div>
        </div>
      </div>

      {/* 총 계약 금액 */}
      <div className="border border-gray-300 p-6 text-center mb-4">
        <p className="text-sm text-gray-600 mb-2">총 계약 금액</p>
        <p className="text-3xl font-bold">
          ₩ {formatAmount(finalTotal)}
        </p>
        <p className="text-sm text-gray-600 mt-1">(부가세 포함)</p>
      </div>

      {/* 금액 계산 */}
      <div className="border border-gray-300 mb-4">
        <table className="w-full text-sm">
          <tbody>
            <tr className="border-b border-gray-300">
              <td className="p-2 bg-gray-100 border-r border-gray-300 w-32">공급가액</td>
              <td className="p-2 text-right border-r border-gray-300">{formatAmount(subtotal)}</td>
              <td className="p-2 bg-gray-100 border-r border-gray-300 w-32">할인율</td>
              <td className="p-2 text-right">{Number.isInteger(discountRate) ? discountRate : Math.round(discountRate)}%</td>
            </tr>
            <tr className="border-b border-gray-300">
              <td className="p-2 bg-gray-100 border-r border-gray-300">할인액</td>
              <td className="p-2 text-right border-r border-gray-300 text-red-600">{discountAmount > 0 ? `-${formatAmount(discountAmount)}` : formatAmount(discountAmount)}</td>
              <td className="p-2 bg-gray-100 border-r border-gray-300">할인 후 공급가액</td>
              <td className="p-2 text-right">{formatAmount(afterDiscount)}</td>
            </tr>
            <tr>
              <td className="p-2 bg-gray-100 border-r border-gray-300">부가세(10%)</td>
              <td className="p-2 text-right border-r border-gray-300">{formatAmount(vat)}</td>
              <td className="p-2 bg-gray-100 border-r border-gray-300 font-medium">합계</td>
              <td className="p-2 text-right font-semibold">{formatAmount(finalTotal)}</td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* 특이사항 */}
      <div className="border border-gray-300">
        <div className="bg-gray-800 text-white p-2 text-sm font-medium text-center">
          특이사항
        </div>
        <div className="p-3 min-h-[60px] text-sm">
          {remarks || "-"}
        </div>
      </div>
    </div>
  );
}