'use client';

/**
 * 제품검사요청서 모달
 *
 * 양식 기반 전환:
 * - getFqcRequestTemplate()로 template 66 조회
 * - requestDocumentId가 있으면 EAV 문서 로드 → FqcRequestDocumentContent로 렌더링
 * - Lazy Snapshot: rendered_html이 없으면 렌더링 완료 후 자동 캡처/저장
 * - Fallback: template 로드 실패 시 기존 InspectionRequestDocument 사용
 */

import { useState, useEffect, useRef, useCallback } from 'react';
import { Loader2, AlertCircle } from 'lucide-react';
import { DocumentViewer } from '@/components/document-system';
import { FqcRequestDocumentContent } from './FqcRequestDocumentContent';
import { InspectionRequestDocument } from './InspectionRequestDocument';
import { getFqcRequestTemplate, getFqcDocument, patchDocumentSnapshot } from '../fqcActions';
import type { InspectionRequestDocument as InspectionRequestDocumentType } from '../types';
import type { FqcTemplate, FqcDocument } from '../fqcActions';

interface InspectionRequestModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  data: InspectionRequestDocumentType | null;
  /** EAV 요청서 문서 ID (API에서 자동생성된 Document ID) */
  requestDocumentId?: number | null;
}

export function InspectionRequestModal({
  open,
  onOpenChange,
  data,
  requestDocumentId,
}: InspectionRequestModalProps) {
  const contentWrapperRef = useRef<HTMLDivElement>(null);
  const snapshotSentRef = useRef(false);

  // FQC 양식/문서 상태
  const [fqcTemplate, setFqcTemplate] = useState<FqcTemplate | null>(null);
  const [fqcDocument, setFqcDocument] = useState<FqcDocument | null>(null);
  const [templateLoadFailed, setTemplateLoadFailed] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const useFqcMode = !templateLoadFailed && !!fqcTemplate;

  // 모달 열릴 때 초기화
  useEffect(() => {
    if (open) {
      setTemplateLoadFailed(false);
      setFqcDocument(null);
      snapshotSentRef.current = false;
    }
  }, [open]);

  // 양식 로드
  useEffect(() => {
    if (!open || fqcTemplate || templateLoadFailed) return;
    setIsLoading(true);
    getFqcRequestTemplate()
      .then(result => {
        if (result.success && result.data) {
          setFqcTemplate(result.data);
        } else {
          setTemplateLoadFailed(true);
        }
      })
      .finally(() => setIsLoading(false));
  }, [open, fqcTemplate, templateLoadFailed]);

  // EAV 문서 로드 (requestDocumentId가 있는 경우)
  useEffect(() => {
    if (!open || !requestDocumentId || !fqcTemplate) return;
    setIsLoading(true);
    getFqcDocument(requestDocumentId)
      .then(result => {
        if (result.success && result.data) {
          setFqcDocument(result.data);
        }
      })
      .finally(() => setIsLoading(false));
  }, [open, requestDocumentId, fqcTemplate]);

  // Lazy Snapshot: FQC 모드 렌더링 완료 후 rendered_html 캡처
  const captureSnapshot = useCallback(() => {
    if (snapshotSentRef.current || !requestDocumentId || !contentWrapperRef.current) return;

    // 렌더링 완료 대기 (다음 프레임)
    requestAnimationFrame(() => {
      const html = contentWrapperRef.current?.innerHTML;
      if (html && html.length > 50) {
        snapshotSentRef.current = true;
        patchDocumentSnapshot(requestDocumentId, html).catch(() => {
          // 실패해도 UI에 영향 없음
        });
      }
    });
  }, [requestDocumentId]);

  // FQC 문서 렌더링 완료 시 스냅샷 캡처
  useEffect(() => {
    if (!useFqcMode || isLoading || !fqcDocument) return;
    captureSnapshot();
  }, [useFqcMode, isLoading, fqcDocument, captureSnapshot]);

  if (!data && !useFqcMode) return null;

  const documentNo = fqcDocument?.documentNo ?? data?.documentNumber;
  const createdDate = data?.createdDate;

  const pdfMeta = documentNo
    ? { documentNumber: documentNo, createdDate: createdDate ?? '' }
    : undefined;

  return (
    <DocumentViewer
      title="제품검사요청서"
      preset="readonly"
      open={open}
      onOpenChange={onOpenChange}
      pdfMeta={pdfMeta}
    >
      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
          <span className="ml-2 text-muted-foreground">양식 로딩 중...</span>
        </div>
      ) : useFqcMode && fqcDocument ? (
        <div ref={contentWrapperRef}>
          <FqcRequestDocumentContent
            template={fqcDocument.template ?? fqcTemplate}
            documentData={fqcDocument.data}
            documentNo={documentNo}
            createdDate={createdDate}
            readonly={true}
          />
        </div>
      ) : data ? (
        <InspectionRequestDocument data={data} />
      ) : (
        <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
          <AlertCircle className="w-8 h-8 mb-2" />
          <p>요청서 데이터가 없습니다.</p>
        </div>
      )}
    </DocumentViewer>
  );
}
