'use client';

/**
 * 연결 문서 콘텐츠 컴포넌트
 *
 * 문서관리에서 생성된 검사 성적서, 작업일지 등을
 * 결재함 모달에서 렌더링합니다.
 */

import { ApprovalLineBox } from './ApprovalLineBox';
import type { LinkedDocumentData } from './types';
import { DocumentHeader } from '@/components/document-system';
import { Badge } from '@/components/ui/badge';
import { FileText, Paperclip } from 'lucide-react';

interface LinkedDocumentContentProps {
  data: LinkedDocumentData;
}

const STATUS_LABELS: Record<string, string> = {
  DRAFT: '임시저장',
  PENDING: '진행중',
  APPROVED: '승인완료',
  REJECTED: '반려',
  CANCELLED: '회수',
};

const STATUS_COLORS: Record<string, string> = {
  DRAFT: 'bg-gray-100 text-gray-800',
  PENDING: 'bg-yellow-100 text-yellow-800',
  APPROVED: 'bg-green-100 text-green-800',
  REJECTED: 'bg-red-100 text-red-800',
  CANCELLED: 'bg-gray-100 text-gray-600',
};

export function LinkedDocumentContent({ data }: LinkedDocumentContentProps) {
  return (
    <div className="bg-white p-8 min-h-full">
      {/* 문서 헤더 (공통 컴포넌트) */}
      <DocumentHeader
        title={data.templateName || '문서 결재'}
        subtitle={`문서번호: ${data.documentNo} | 작성일자: ${data.createdAt?.substring(0, 10) || '-'}`}
        layout="centered"
        customApproval={<ApprovalLineBox drafter={data.drafter} approvers={data.approvers} />}
      />

      {/* 문서 기본 정보 */}
      <div className="border border-gray-300 mb-4">
        <div className="flex border-b border-gray-300">
          <div className="w-28 bg-gray-100 p-3 font-medium text-sm border-r border-gray-300">
            문서 제목
          </div>
          <div className="flex-1 p-3 text-sm">{data.title || '-'}</div>
        </div>
        <div className="grid grid-cols-2 border-b border-gray-300">
          <div className="flex border-r border-gray-300">
            <div className="w-28 bg-gray-100 p-3 font-medium text-sm border-r border-gray-300">
              양식
            </div>
            <div className="flex-1 p-3 text-sm flex items-center gap-2">
              <FileText className="w-4 h-4 text-gray-500" />
              {data.templateName || '-'}
            </div>
          </div>
          <div className="flex">
            <div className="w-28 bg-gray-100 p-3 font-medium text-sm border-r border-gray-300">
              상태
            </div>
            <div className="flex-1 p-3 text-sm">
              <Badge className={STATUS_COLORS[data.status] || 'bg-gray-100 text-gray-800'}>
                {STATUS_LABELS[data.status] || data.status}
              </Badge>
            </div>
          </div>
        </div>
      </div>

      {/* 문서 데이터 */}
      {data.documentData.length > 0 && (
        <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="divide-y divide-gray-300">
            {data.documentData.map((field, index) => (
              <div key={index} className="flex">
                <div className="w-36 bg-gray-100 p-3 font-medium text-sm border-r border-gray-300">
                  {field.fieldLabel}
                </div>
                <div className="flex-1 p-3 text-sm whitespace-pre-wrap">
                  {renderFieldValue(field.value)}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 첨부파일 */}
      {data.attachments && data.attachments.length > 0 && (
        <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-4 space-y-2">
            {data.attachments.map((file) => (
              <a
                key={file.id}
                href={file.url}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-2 text-sm text-blue-600 hover:underline"
              >
                <Paperclip className="w-4 h-4" />
                {file.name}
              </a>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function renderFieldValue(value: unknown): string {
  if (value === null || value === undefined) return '-';
  if (typeof value === 'string') return value || '-';
  if (typeof value === 'number') return String(value);
  if (typeof value === 'boolean') return value ? '예' : '아니오';
  if (Array.isArray(value)) return value.join(', ') || '-';
  if (typeof value === 'object') return JSON.stringify(value, null, 2);
  return String(value);
}
