'use client';

/**
 * 비용견적서 문서 컴포넌트
 *
 * 공통 컴포넌트 사용:
 * - DocumentHeader: centered 레이아웃 + customApproval (ApprovalLineBox)
 */

import { Fragment } from 'react';
import { ApprovalLineBox } from './ApprovalLineBox';
import type { ExpenseEstimateDocumentData } from './types';
import { DocumentHeader } from '@/components/document-system';
import { formatNumber as formatCurrency } from '@/lib/utils/amount';

interface ExpenseEstimateDocumentProps {
  data: ExpenseEstimateDocumentData;
}

export function ExpenseEstimateDocument({ data }: ExpenseEstimateDocumentProps) {

  // 월별 그룹핑
  const groupedByMonth = data.items.reduce((acc, item) => {
    const month = item.expectedPaymentDate.substring(0, 7); // YYYY-MM
    if (!acc[month]) {
      acc[month] = [];
    }
    acc[month].push(item);
    return acc;
  }, {} as Record<string, typeof data.items>);

  const getMonthSubtotal = (monthItems: typeof data.items) => {
    return monthItems.reduce((sum, item) => sum + item.amount, 0);
  };

  const getMonthLabel = (month: string) => {
    const [year, mon] = month.split('-');
    return `${year}년 ${parseInt(mon)}월 계`;
  };

  return (
    <div className="bg-white p-8 min-h-full">
      {/* 문서 헤더 (공통 컴포넌트) */}
      <DocumentHeader
        title="비용견적서"
        subtitle={`문서번호: ${data.documentNo} | 작성일자: ${data.createdAt}`}
        layout="centered"
        customApproval={<ApprovalLineBox drafter={data.drafter} approvers={data.approvers} />}
      />

      {/* 문서 내용 */}
      <div className="border border-gray-300">
        {/* 비용견적서 헤더 */}
        <div className="bg-gray-800 text-white p-2 text-sm font-medium text-center">
          비용견적서 목록
        </div>

        {/* 테이블 */}
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-gray-100 border-b border-gray-300">
              <th className="p-2 text-center font-medium border-r border-gray-300 w-32">예상 지급일</th>
              <th className="p-2 text-left font-medium border-r border-gray-300">항목</th>
              <th className="p-2 text-right font-medium border-r border-gray-300 w-32">지출금액</th>
              <th className="p-2 text-left font-medium border-r border-gray-300 w-24">거래처</th>
              <th className="p-2 text-left font-medium w-40">계좌</th>
            </tr>
          </thead>
          <tbody>
            {Object.entries(groupedByMonth).map(([month, monthItems]) => (
              <Fragment key={month}>
                {monthItems.map((item) => (
                  <tr key={item.id} className="border-b border-gray-300">
                    <td className="p-2 text-center border-r border-gray-300">{item.expectedPaymentDate}</td>
                    <td className="p-2 border-r border-gray-300">{item.category}</td>
                    <td className="p-2 text-right border-r border-gray-300 text-blue-600 font-medium">
                      {formatCurrency(item.amount)}
                    </td>
                    <td className="p-2 border-r border-gray-300">{item.vendor}</td>
                    <td className="p-2">{item.account}</td>
                  </tr>
                ))}
                {/* 월별 소계 */}
                <tr className="bg-pink-50 border-b border-gray-300">
                  <td colSpan={2} className="p-2 font-medium border-r border-gray-300">
                    {getMonthLabel(month)}
                  </td>
                  <td className="p-2 text-right border-r border-gray-300 text-red-600 font-bold">
                    {formatCurrency(getMonthSubtotal(monthItems))}
                  </td>
                  <td colSpan={2} className="p-2"></td>
                </tr>
              </Fragment>
            ))}

            {/* 지출 합계 */}
            <tr className="bg-gray-100 border-b border-gray-300">
              <td colSpan={2} className="p-3 font-semibold border-r border-gray-300">지출 합계</td>
              <td className="p-3 text-right border-r border-gray-300 text-red-600 font-bold">
                {formatCurrency(data.totalExpense)}
              </td>
              <td colSpan={2} className="p-3"></td>
            </tr>

            {/* 계좌 잔액 */}
            <tr className="bg-gray-100 border-b border-gray-300">
              <td colSpan={2} className="p-3 font-semibold border-r border-gray-300">계좌 잔액</td>
              <td className="p-3 text-right border-r border-gray-300 font-bold">
                {formatCurrency(data.accountBalance)}
              </td>
              <td colSpan={2} className="p-3"></td>
            </tr>

            {/* 최종 차액 */}
            <tr className="bg-gray-100">
              <td colSpan={2} className="p-3 font-semibold border-r border-gray-300">최종 차액</td>
              <td className={`p-3 text-right border-r border-gray-300 font-bold ${data.finalDifference >= 0 ? 'text-blue-600' : 'text-red-600'}`}>
                {formatCurrency(data.finalDifference)}
              </td>
              <td colSpan={2} className="p-3"></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}
