'use client';

/**
 * 견적서 문서 모달
 *
 * document-system 통합 버전 (2026-01-22)
 * - DocumentViewer 사용
 * - EstimateDocumentContent로 문서 본문 분리
 */

import { useCallback, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Pencil, Send } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DocumentViewer } from '@/components/document-system';
import type { EstimateDetailFormData } from '../types';
import { getCompanyInfo, type CompanyInfo } from '../actions';
import { EstimateDocumentContent } from './EstimateDocumentContent';

interface EstimateDocumentModalProps {
  isOpen: boolean;
  onClose: () => void;
  formData: EstimateDetailFormData;
  estimateId?: string;
}

export function EstimateDocumentModal({
  isOpen,
  onClose,
  formData,
  estimateId,
}: EstimateDocumentModalProps) {
  const router = useRouter();

  // 회사 정보 상태
  const [companyInfo, setCompanyInfo] = useState<CompanyInfo | null>(null);

  // 회사 정보 로드
  useEffect(() => {
    if (isOpen) {
      getCompanyInfo().then((result) => {
        if (result.success && result.data) {
          setCompanyInfo(result.data);
        }
      });
    }
  }, [isOpen]);

  // 수정 페이지로 이동
  const handleEdit = useCallback(() => {
    if (estimateId) {
      onClose();
      router.push(`/ko/construction/project/bidding/estimates/${estimateId}?mode=edit`);
    }
  }, [estimateId, onClose, router]);

  // 툴바 확장 버튼들
  const toolbarExtra = (
    <>
      <Button variant="outline" size="sm" onClick={handleEdit} disabled={!estimateId}>
        <Pencil className="h-4 w-4 mr-1" />
        수정
      </Button>
      <Button variant="default" size="sm" className="bg-blue-600 hover:bg-blue-700">
        <Send className="h-4 w-4 mr-1" />
        상신
      </Button>
    </>
  );

  return (
    <DocumentViewer
      title="견적서 상세"
      preset="inspection"
      open={isOpen}
      onOpenChange={(open) => !open && onClose()}
      toolbarExtra={toolbarExtra}
    >
      <EstimateDocumentContent
        data={{
          formData,
          companyInfo,
        }}
      />
    </DocumentViewer>
  );
}
