'use client';

/**
 * 견적서 문서 콘텐츠
 *
 * DocumentViewer와 함께 사용하는 문서 본문 컴포넌트
 *
 * 공통 컴포넌트 사용:
 * - DocumentHeader: centered 레이아웃 + 3col 결재란
 */

import type { EstimateDetailFormData } from '../types';
import type { CompanyInfo } from '../actions';
import { DocumentHeader } from '@/components/document-system';
import { formatNumber } from '@/lib/utils/amount';

// 금액을 한글로 변환
function amountToKorean(amount: number): string {
  const units = ['', '만', '억', '조'];
  const smallUnits = ['', '십', '백', '천'];
  const digits = ['', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'];

  if (amount === 0) return '영';

  let result = '';
  let unitIndex = 0;

  while (amount > 0) {
    const segment = amount % 10000;
    if (segment > 0) {
      let segmentStr = '';
      let segmentNum = segment;
      for (let i = 0; i < 4 && segmentNum > 0; i++) {
        const digit = segmentNum % 10;
        if (digit > 0) {
          segmentStr = digits[digit] + smallUnits[i] + segmentStr;
        }
        segmentNum = Math.floor(segmentNum / 10);
      }
      result = segmentStr + units[unitIndex] + result;
    }
    amount = Math.floor(amount / 10000);
    unitIndex++;
  }

  return '(금)' + result;
}

interface EstimateDocumentContentProps {
  data: {
    formData: EstimateDetailFormData;
    companyInfo: CompanyInfo | null;
  };
}

export function EstimateDocumentContent({ data }: EstimateDocumentContentProps) {
  const { formData, companyInfo } = data;

  // 견적서 문서 데이터
  const documentData = {
    documentNo: formData.estimateCode || '',
    createdDate: formData.siteBriefing.briefingDate || '',
    recipient: formData.siteBriefing.partnerName || '',
    companyName: companyInfo?.companyName || formData.siteBriefing.companyName || '',
    projectName: formData.bidInfo.projectName || '',
    address: companyInfo?.address || '',
    amount: formData.summaryItems.reduce((sum, item) => sum + item.totalCost, 0),
    date: formData.bidInfo.bidDate || '',
    manager: companyInfo?.managerName || formData.estimateCompanyManager || '',
    managerContact: companyInfo?.managerPhone || formData.estimateCompanyManagerContact || '',
    contact: {
      hp: companyInfo?.managerPhone || '',
      tel: companyInfo?.phone || '',
      fax: companyInfo?.fax || '',
    },
  };

  return (
    <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
      {/* 상단: 제목 + 결재란 (공통 컴포넌트) */}
      <DocumentHeader
        title="견 적 서"
        subtitle={`문서번호: ${documentData.documentNo} | 작성일자: ${documentData.createdDate}`}
        layout="centered"
        approval={{
          type: '3col',
          writer: { name: formData.estimatorName || '' },
          showDepartment: false,
        }}
      />

      {/* 기본 정보 테이블 */}
      <table className="w-full border-collapse mb-6 text-sm">
        <tbody>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 w-20 text-center">귀중</td>
            <td className="border border-gray-400 px-3 py-2 w-1/4">회사명</td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 w-20 text-center">회사명</td>
            <td className="border border-gray-400 px-3 py-2 w-1/4">{documentData.companyName}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 text-center">현장명</td>
            <td className="border border-gray-400 px-3 py-2">{documentData.projectName || '현장명'}</td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 text-center">주소</td>
            <td className="border border-gray-400 px-3 py-2">{documentData.address || '주소명'}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 text-center">금액</td>
            <td className="border border-gray-400 px-3 py-2">
              {amountToKorean(documentData.amount)} 원정
            </td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 text-center">일자</td>
            <td className="border border-gray-400 px-3 py-2">{documentData.date}</td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 text-center">담당자</td>
            <td className="border border-gray-400 px-3 py-2"></td>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 text-center" rowSpan={2}>연락처</td>
            <td className="border border-gray-400 px-3 py-2" rowSpan={2}>
              <div className="space-y-0.5 text-xs">
                <div>담당자 : {documentData.manager}</div>
                <div>H . P : {documentData.contact.hp}</div>
                <div>T E L : {documentData.contact.tel}</div>
                <div>F A X : {documentData.contact.fax}</div>
              </div>
            </td>
          </tr>
          <tr>
            <td className="border border-gray-400 px-3 py-2 bg-gray-100 text-center">연락처</td>
            <td className="border border-gray-400 px-3 py-2"></td>
          </tr>
        </tbody>
      </table>

      {/* 안내 문구 */}
      <p className="text-sm mb-6">하기와 같이 見積합니다.</p>

      {/* 견적 요약 테이블 */}
      <div className="mb-6">
        <div className="mb-2">
          <span className="text-sm font-medium">견적 요약</span>
        </div>
        <table className="w-full border-collapse text-sm">
          <thead>
            <tr className="bg-gray-100">
              <th className="border border-gray-400 px-3 py-2">명 칭</th>
              <th className="border border-gray-400 px-3 py-2 w-16">수량</th>
              <th className="border border-gray-400 px-3 py-2 w-16">단위</th>
              <th className="border border-gray-400 px-3 py-2 w-24">재 료 비</th>
              <th className="border border-gray-400 px-3 py-2 w-24">노 무 비</th>
              <th className="border border-gray-400 px-3 py-2 w-24">합 계</th>
              <th className="border border-gray-400 px-3 py-2 w-20">비 고</th>
            </tr>
          </thead>
          <tbody>
            {formData.summaryItems.length === 0 ? (
              <tr>
                <td colSpan={7} className="border border-gray-400 px-3 py-4 text-center text-gray-500">
                  등록된 항목이 없습니다.
                </td>
              </tr>
            ) : (
              formData.summaryItems.map((item) => (
                <tr key={item.id}>
                  <td className="border border-gray-400 px-3 py-2">{item.name}</td>
                  <td className="border border-gray-400 px-3 py-2 text-center">{item.quantity}</td>
                  <td className="border border-gray-400 px-3 py-2 text-center">{item.unit}</td>
                  <td className="border border-gray-400 px-3 py-2 text-right">{formatNumber(item.materialCost)}</td>
                  <td className="border border-gray-400 px-3 py-2 text-right">{formatNumber(item.laborCost)}</td>
                  <td className="border border-gray-400 px-3 py-2 text-right font-medium">{formatNumber(item.totalCost)}</td>
                  <td className="border border-gray-400 px-3 py-2">{item.remarks}</td>
                </tr>
              ))
            )}
            {/* 합계 행 */}
            <tr className="font-medium">
              <td className="border border-gray-400 px-3 py-2 text-center" colSpan={3}>합 계</td>
              <td className="border border-gray-400 px-3 py-2 text-right">
                {formatNumber(formData.summaryItems.reduce((sum, item) => sum + item.materialCost, 0))}
              </td>
              <td className="border border-gray-400 px-3 py-2 text-right">
                {formatNumber(formData.summaryItems.reduce((sum, item) => sum + item.laborCost, 0))}
              </td>
              <td className="border border-gray-400 px-3 py-2 text-right">
                ￦{formatNumber(formData.summaryItems.reduce((sum, item) => sum + item.totalCost, 0))}
              </td>
              <td className="border border-gray-400 px-3 py-2"></td>
            </tr>
            {/* 특기사항 행 */}
            <tr>
              <td colSpan={7} className="border border-gray-400 px-3 py-2 text-sm">
                * 특기사항 : 부가세 별도 / 현설조건에 따름
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* 견적 상세 테이블 */}
      <div className="mb-6">
        <div className="mb-2">
          <span className="text-sm font-medium">견적 상세</span>
        </div>
        <table className="w-full border-collapse text-xs">
          <thead>
            <tr className="bg-gray-100">
              <th className="border border-gray-400 px-2 py-1 w-8" rowSpan={2}>NO</th>
              <th className="border border-gray-400 px-2 py-1" rowSpan={2}>명칭</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={2}>규 격(mm)</th>
              <th className="border border-gray-400 px-2 py-1" rowSpan={2}>수량</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={2}>재 료 비</th>
              <th className="border border-gray-400 px-2 py-1" colSpan={2}>노 무 비</th>
              <th className="border border-gray-400 px-2 py-1" colSpan={2}>합 계</th>
            </tr>
            <tr className="bg-gray-100">
              <th className="border border-gray-400 px-2 py-1">가로(W)</th>
              <th className="border border-gray-400 px-2 py-1">높이(H)</th>
              <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">단가</th>
              <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">금액</th>
            </tr>
          </thead>
          <tbody>
            {formData.detailItems.length === 0 ? (
              <tr>
                <td colSpan={13} className="border border-gray-400 px-3 py-4 text-center text-gray-500">
                  등록된 항목이 없습니다.
                </td>
              </tr>
            ) : (
              formData.detailItems.map((item, index) => (
                <tr key={item.id}>
                  <td className="border border-gray-400 px-2 py-1 text-center">{index + 1}</td>
                  <td className="border border-gray-400 px-2 py-1">{item.name}</td>
                  <td className="border border-gray-400 px-2 py-1">{item.material}</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.width)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.height)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">{item.quantity}</td>
                  <td className="border border-gray-400 px-2 py-1 text-center">SET</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.unitPrice)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.materialCost)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.laborCost)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.laborCost * item.quantity)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.totalPrice)}</td>
                  <td className="border border-gray-400 px-2 py-1 text-right">{formatNumber(item.totalCost)}</td>
                </tr>
              ))
            )}
            {/* 합계 행 */}
            <tr className="font-medium">
              <td className="border border-gray-400 px-2 py-1 text-center" colSpan={5}>합 계</td>
              <td className="border border-gray-400 px-2 py-1 text-center">
                {formData.detailItems.reduce((sum, item) => sum + item.quantity, 0)}
              </td>
              <td className="border border-gray-400 px-2 py-1 text-center">SET</td>
              <td className="border border-gray-400 px-2 py-1"></td>
              <td className="border border-gray-400 px-2 py-1 text-right">
                {formatNumber(formData.detailItems.reduce((sum, item) => sum + item.materialCost, 0))}
              </td>
              <td className="border border-gray-400 px-2 py-1"></td>
              <td className="border border-gray-400 px-2 py-1 text-right">
                {formatNumber(formData.detailItems.reduce((sum, item) => sum + item.laborCost * item.quantity, 0))}
              </td>
              <td className="border border-gray-400 px-2 py-1"></td>
              <td className="border border-gray-400 px-2 py-1 text-right">
                {formatNumber(formData.detailItems.reduce((sum, item) => sum + item.totalCost, 0))}
              </td>
            </tr>
            {/* 비고 행 */}
            <tr>
              <td colSpan={13} className="border border-gray-400 px-2 py-1 text-sm">
                * 비고 :
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}
