'use client';

/**
 * 동적 양식 문서 컴포넌트
 *
 * API template 기반 동적 폼 데이터를 문서 형태로 렌더링
 */

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

interface DynamicDocumentProps {
  data: DynamicDocumentData;
}

export function DynamicDocument({ data }: DynamicDocumentProps) {
  const fieldEntries = Object.entries(data.fields).filter(
    ([, value]) => value !== undefined && value !== null && value !== ''
  );
  const labels = data.fieldLabels || {};

  return (
    <div className="bg-white p-8 min-h-full">
      {/* 문서 헤더 */}
      <DocumentHeader
        title={data.formName}
        subtitle={`문서번호: ${data.documentNo} | 작성일자: ${data.createdAt}`}
        layout="centered"
        customApproval={<ApprovalLineBox drafter={data.drafter} approvers={data.approvers} />}
      />

      {/* 문서 내용 */}
      <div className="border border-gray-300">
        {fieldEntries.length === 0 ? (
          <div className="p-6 text-center text-sm text-gray-400">
            입력된 내용이 없습니다.
          </div>
        ) : (
          fieldEntries.map(([key, value]) => (
            <div key={key} className="flex border-b border-gray-300 last:border-b-0">
              <div className="w-36 bg-gray-100 p-3 font-medium text-sm border-r border-gray-300 shrink-0">
                {labels[key] || key}
              </div>
              <div className="flex-1 p-3 text-sm">
                {renderFieldValue(value, labels)}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

function renderFieldValue(value: unknown, labels?: Record<string, string>): React.ReactNode {
  if (value === null || value === undefined) return '-';

  // 숫자
  if (typeof value === 'number') {
    return formatNumber(value);
  }

  // 문자열
  if (typeof value === 'string') {
    return value || '-';
  }

  // 불리언
  if (typeof value === 'boolean') {
    return value ? '예' : '아니오';
  }

  // 배열 (테이블 데이터)
  if (Array.isArray(value)) {
    if (value.length === 0) return '-';

    // 객체 배열이면 테이블로 렌더링
    if (typeof value[0] === 'object' && value[0] !== null) {
      const columns = Object.keys(value[0] as Record<string, unknown>);
      return (
        <table className="w-full border text-xs">
          <thead>
            <tr className="bg-gray-50">
              <th className="border px-2 py-1 w-10">No</th>
              {columns.map((col) => (
                <th key={col} className="border px-2 py-1">{labels?.[col] || col}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {value.map((row, idx) => (
              <tr key={idx}>
                <td className="border px-2 py-1 text-center">{idx + 1}</td>
                {columns.map((col) => (
                  <td key={col} className="border px-2 py-1">
                    {formatCellValue((row as Record<string, unknown>)[col])}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      );
    }

    // 단순 배열
    return value.join(', ');
  }

  // 날짜 범위 객체
  if (typeof value === 'object' && value !== null) {
    const obj = value as Record<string, unknown>;
    if ('start' in obj && 'end' in obj) {
      return `${obj.start || '-'} ~ ${obj.end || '-'}`;
    }
    return JSON.stringify(value);
  }

  return String(value);
}

function formatCellValue(value: unknown): string {
  if (value === null || value === undefined) return '-';
  if (typeof value === 'number') return formatNumber(value);
  return String(value);
}
