"use client";

import React, { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle, Loader2, Save } from 'lucide-react';
import { DocumentViewer } from '@/components/document-system';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { Document, DocumentItem } from '../types';
import { MOCK_SHIPMENT_DETAIL } from '../mockData';

// 기존 문서 컴포넌트 import
import { DeliveryConfirmation } from '@/components/outbound/ShipmentManagement/documents/DeliveryConfirmation';
import { ShippingSlip } from '@/components/outbound/ShipmentManagement/documents/ShippingSlip';

// 수주서 문서 컴포넌트 import
import { SalesOrderDocument } from '@/components/orders/documents/SalesOrderDocument';
import type { ProductInfo } from '@/components/orders/documents/OrderDocumentModal';
import type { OrderItem } from '@/components/orders/actions';

// 품질검사 문서 컴포넌트 import
import {
  ImportInspectionDocument,
  JointbarInspectionDocument,
  QualityDocumentUploader,
} from './documents';

// 제품검사 성적서 (신규 양식) import
import { InspectionReportDocument } from '@/components/quality/InspectionManagement/documents/InspectionReportDocument';
import { mockReportInspectionItems } from '@/components/quality/InspectionManagement/mockData';
import type { InspectionReportDocument as InspectionReportDocumentType } from '@/components/quality/InspectionManagement/types';
import type { ImportInspectionTemplate, ImportInspectionRef, InspectionItemValue } from './documents/ImportInspectionDocument';

// 작업일지 + 중간검사 성적서 문서 컴포넌트 import (공정별 신규 버전)
import {
  ScreenWorkLogContent,
  SlatWorkLogContent,
  BendingWorkLogContent,
  ScreenInspectionContent,
  SlatInspectionContent,
  BendingInspectionContent,
} from '@/components/production/WorkOrders/documents';
import type { WorkOrder } from '@/components/production/WorkOrders/types';

// 검사 템플릿 API
import { getInspectionTemplate } from '@/components/material/ReceivingManagement/actions';

/**
 * 저장된 document.data (field_key 기반)를 ImportInspectionDocument의 initialValues로 변환
 *
 * field_key 패턴:
 * - {itemId}_n{1,2,3} → numeric 측정값
 * - {itemId}_okng_n{1,2,3} → OK/NG 값
 * - {itemId}_result → 항목별 판정
 */
function parseSavedDataToInitialValues(
  tmpl: ImportInspectionTemplate,
  docData: Array<{ field_key: string; field_value: string | null }>
): InspectionItemValue[] {
  // field_key → value 맵 생성
  const dataMap = new Map<string, string>();
  for (const d of docData) {
    if (d.field_value) dataMap.set(d.field_key, d.field_value);
  }

  return tmpl.inspectionItems.map((item) => {
    const isOkng = item.measurementType === 'okng';
    const measurements: (number | 'OK' | 'NG' | null)[] = Array(item.measurementCount).fill(null);

    for (let n = 0; n < item.measurementCount; n++) {
      if (isOkng) {
        const val = dataMap.get(`${item.id}_okng_n${n + 1}`);
        if (val === 'ok') measurements[n] = 'OK';
        else if (val === 'ng') measurements[n] = 'NG';
      } else {
        const val = dataMap.get(`${item.id}_n${n + 1}`);
        if (val) {
          const num = parseFloat(val);
          measurements[n] = isNaN(num) ? null : num;
        }
      }
    }

    // 항목별 판정
    const resultVal = dataMap.get(`${item.id}_result`);
    let result: 'OK' | 'NG' | null = null;
    if (resultVal === 'ok') result = 'OK';
    else if (resultVal === 'ng') result = 'NG';

    return { itemId: item.id, measurements, result };
  });
}

interface InspectionModalProps {
  isOpen: boolean;
  onClose: () => void;
  document: Document | null;
  documentItem: DocumentItem | null;
  // 수입검사 템플릿 로드용 추가 props
  itemId?: number;  // 품목 ID (실제 API로 템플릿 조회 시 사용)
  itemName?: string;
  specification?: string;
  supplier?: string;
  inspector?: string;  // 검사자 (현재 로그인 사용자)
  inspectorDept?: string; // 검사자 부서
  lotSize?: number;    // 로트크기 (입고수량)
  materialNo?: string; // 자재번호
  // 읽기 전용 모드 (QMS 심사 확인용)
  readOnly?: boolean;
}

// 문서 타입별 정보
const DOCUMENT_INFO: Record<string, { label: string; hasTemplate: boolean; color: string }> = {
  import: { label: '수입검사 성적서', hasTemplate: true, color: 'text-green-600' },
  order: { label: '수주서', hasTemplate: true, color: 'text-blue-600' },
  log: { label: '작업일지', hasTemplate: true, color: 'text-orange-500' },
  report: { label: '중간검사 성적서', hasTemplate: true, color: 'text-blue-500' },
  confirmation: { label: '납품확인서', hasTemplate: true, color: 'text-red-500' },
  shipping: { label: '출고증', hasTemplate: true, color: 'text-gray-600' },
  product: { label: '제품검사 성적서', hasTemplate: true, color: 'text-green-500' },
  quality: { label: '품질관리서', hasTemplate: false, color: 'text-purple-600' },
};

// Placeholder 컴포넌트 (양식 대기 문서용)
const PlaceholderDocument = ({ docType, docItem }: { docType: string; docItem: DocumentItem | null }) => {
  const info = DOCUMENT_INFO[docType] || { label: '문서', hasTemplate: false, color: 'text-gray-600' };

  return (
    <div className="bg-white shadow-sm p-16 w-full h-full rounded flex flex-col items-center justify-center text-center">
      <div className="w-16 h-16 text-amber-500 mb-4 mx-auto">
        <AlertCircle className="w-full h-full" />
      </div>
      <h2 className="text-xl font-bold text-gray-800 mb-2">{info.label}</h2>
      <p className="text-gray-500 text-sm mb-2">{docItem?.title || '문서'}</p>
      {docItem?.date && (
        <p className="text-gray-400 text-xs mb-2">{docItem.date}</p>
      )}
      {docItem?.code && (
        <p className="text-xs text-green-600 font-mono bg-green-50 px-2 py-1 rounded mb-4">
          로트 번호: {docItem.code}
        </p>
      )}
      <div className="mt-4 p-4 bg-amber-50 rounded-lg border border-amber-200">
        <p className="text-amber-700 text-sm font-medium">양식 준비 중</p>
        <p className="text-amber-600 text-xs mt-1">디자인 파일이 필요합니다</p>
      </div>
    </div>
  );
};

// QMS용 수주서 Mock 데이터
const QMS_MOCK_PRODUCTS: ProductInfo[] = [
  { productName: '방화 스크린 셔터 (표준형)', productCategory: '스크린', openWidth: '3000', openHeight: '2500', quantity: 5, floor: '1F', code: 'FSS-01' },
  { productName: '방화 스크린 셔터 (방화형)', productCategory: '스크린', openWidth: '3000', openHeight: '2500', quantity: 3, floor: '2F', code: 'FSS-02' },
];
const QMS_MOCK_ORDER_ITEMS: OrderItem[] = [
  { id: 'mt-1', itemCode: 'MT-001', itemName: '모터(380V 단상)', specification: '150K', type: '모터', quantity: 8, unit: 'EA', unitPrice: 120000, supplyAmount: 960000, taxAmount: 96000, totalAmount: 1056000, sortOrder: 1 },
  { id: 'br-1', itemCode: 'BR-001', itemName: '브라켓트', specification: '380X180 [2-4"]', type: '브라켓', quantity: 16, unit: 'EA', unitPrice: 15000, supplyAmount: 240000, taxAmount: 24000, totalAmount: 264000, sortOrder: 2 },
  { id: 'gr-1', itemCode: 'GR-001', itemName: '가이드레일 백면형 (120X70)', specification: 'EGI 1.5ST', type: '가이드레일', quantity: 16, unit: 'EA', unitPrice: 25000, supplyAmount: 400000, taxAmount: 40000, totalAmount: 440000, width: 120, height: 2500, sortOrder: 3 },
  { id: 'cs-1', itemCode: 'CS-001', itemName: '케이스(셔터박스)', specification: 'EGI 1.5ST 380X180', type: '케이스', quantity: 8, unit: 'EA', unitPrice: 35000, supplyAmount: 280000, taxAmount: 28000, totalAmount: 308000, width: 380, height: 180, sortOrder: 4 },
  { id: 'bf-1', itemCode: 'BF-001', itemName: '하단마감재', specification: 'EGI 1.5ST', type: '하단마감재', quantity: 8, unit: 'EA', unitPrice: 18000, supplyAmount: 144000, taxAmount: 14400, totalAmount: 158400, sortOrder: 5 },
];

// QMS용 제품검사 성적서 Mock 데이터
const QMS_MOCK_REPORT_DATA: InspectionReportDocumentType = {
  documentNumber: 'RPT-KD-SS-2024-530',
  createdDate: '2024-09-24',
  approvalLine: [
    { role: '작성', name: '김검사', department: '품질관리부' },
    { role: '승인', name: '박승인', department: '품질관리부' },
  ],
  productName: '방화스크린',
  productLotNo: 'KD-SS-240924-19',
  productCode: 'WY-SC780',
  lotSize: '8',
  client: '삼성물산(주)',
  inspectionDate: '2024-09-26',
  siteName: '강남 아파트 단지',
  inspector: '김검사',
  inspectionItems: mockReportInspectionItems,
  specialNotes: '',
  finalJudgment: '합격',
};

// QMS용 작업일지 Mock WorkOrder 생성
const createQmsMockWorkOrder = (subType?: string): WorkOrder => ({
  id: 'qms-wo-1',
  workOrderNo: 'KD-WO-240924-01',
  lotNo: 'KD-SS-240924-19',
  processId: 1,
  processName: subType === 'slat' ? '슬랫' : subType === 'bending' ? '절곡' : '스크린',
  processCode: subType || 'screen',
  processType: (subType || 'screen') as 'screen' | 'slat' | 'bending',
  status: 'in_progress',
  client: '삼성물산(주)',
  projectName: '강남 아파트 단지',
  dueDate: '2024-10-05',
  assignee: '김작업',
  assignees: [
    { id: '1', name: '김작업', isPrimary: true },
    { id: '2', name: '이생산', isPrimary: false },
  ],
  orderDate: '2024-09-20',
  scheduledDate: '2024-09-24',
  shipmentDate: '2024-10-04',
  salesOrderDate: '2024-09-18',
  isAssigned: true,
  isStarted: true,
  priority: 3,
  priorityLabel: '긴급',
  shutterCount: 5,
  department: '생산부',
  items: [
    { id: '1', no: 1, status: 'completed', productName: '와이어 스크린', floorCode: '1층/FSS-01', specification: '3000×2500', quantity: 2, unit: 'EA', orderNodeId: null, orderNodeName: '' },
    { id: '2', no: 2, status: 'in_progress', productName: '메쉬 스크린', floorCode: '2층/FSS-03', specification: '3000×2500', quantity: 3, unit: 'EA', orderNodeId: null, orderNodeName: '' },
    { id: '3', no: 3, status: 'waiting', productName: '광폭 와이어', floorCode: '3층/FSS-05', specification: '12000×4500', quantity: 1, unit: 'EA', orderNodeId: null, orderNodeName: '' },
  ],
  currentStep: 2,
  issues: [],
  note: '품질 검수 철저히 진행',
});

// 로딩 컴포넌트
const LoadingDocument = () => (
  <div className="bg-white shadow-sm p-16 w-full h-full rounded flex flex-col items-center justify-center text-center">
    <Loader2 className="w-12 h-12 text-blue-500 animate-spin mb-4" />
    <p className="text-gray-600 text-sm">검사 템플릿을 불러오는 중...</p>
  </div>
);

// 에러 컴포넌트
const ErrorDocument = ({ message, onRetry }: { message: string; onRetry?: () => void }) => (
  <div className="bg-white shadow-sm p-16 w-full h-full rounded flex flex-col items-center justify-center text-center">
    <AlertCircle className="w-12 h-12 text-red-500 mb-4" />
    <p className="text-gray-800 font-medium mb-2">템플릿 로드 실패</p>
    <p className="text-gray-500 text-sm mb-4">{message}</p>
    {onRetry && (
      <button
        onClick={onRetry}
        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm"
      >
        다시 시도
      </button>
    )}
  </div>
);

/**
 * InspectionModal V2
 * - DocumentViewer 시스템 사용
 * - 수입검사: 모달 열릴 때 API로 템플릿 로드 (Lazy Loading)
 */
export const InspectionModal = ({
  isOpen,
  onClose,
  document: doc,
  documentItem,
  itemId,
  itemName,
  specification,
  supplier,
  inspector,
  inspectorDept,
  lotSize,
  materialNo,
  readOnly = false,
}: InspectionModalProps) => {
  // 수입검사 템플릿 상태
  const [importTemplate, setImportTemplate] = useState<ImportInspectionTemplate | null>(null);
  const [importInitialValues, setImportInitialValues] = useState<InspectionItemValue[] | undefined>(undefined);
  const [isLoadingTemplate, setIsLoadingTemplate] = useState(false);
  const [templateError, setTemplateError] = useState<string | null>(null);

  // 수입검사 저장용 ref/상태
  const importDocRef = useRef<ImportInspectionRef>(null);
  const [isSaving, setIsSaving] = useState(false);

  // 수입검사 템플릿 로드 (모달 열릴 때)
  useEffect(() => {
    // itemId가 있으면 실제 API로 조회, 없으면 itemName/specification으로 mock 조회
    if (isOpen && doc?.type === 'import' && (itemId || (itemName && specification))) {
      loadInspectionTemplate();
    }
    // 모달 닫힐 때 상태 초기화
    if (!isOpen) {
      setImportTemplate(null);
      setImportInitialValues(undefined);
      setTemplateError(null);
    }
  }, [isOpen, doc?.type, itemId, itemName, specification]);

  const loadInspectionTemplate = async () => {
    // itemId가 있으면 실제 API 호출, 없으면 itemName/specification 필요
    if (!itemId && (!itemName || !specification)) return;

    setIsLoadingTemplate(true);
    setTemplateError(null);

    try {
      const result = await getInspectionTemplate({
        itemId,
        itemName,
        specification,
        lotNo: documentItem?.code,
        supplier,
        inspector,
        lotSize,
        materialNo,
      });

      if (result.success && result.data) {
        const tmpl = result.data as ImportInspectionTemplate;
        setImportTemplate(tmpl);

        // 저장된 측정값을 initialValues로 변환
        const docData = result.resolveData?.document?.data;
        if (docData && docData.length > 0) {
          const values = parseSavedDataToInitialValues(tmpl, docData.map((d: { field_key: string; field_value?: string | null }) => ({ field_key: d.field_key, field_value: d.field_value ?? null })));
          setImportInitialValues(values);
        } else {
          setImportInitialValues(undefined);
        }
      } else {
        setTemplateError(result.error || '템플릿을 불러올 수 없습니다.');
      }
    } catch (error) {
      console.error('[InspectionModal] loadInspectionTemplate error:', error);
      setTemplateError('템플릿 로드 중 오류가 발생했습니다.');
    } finally {
      setIsLoadingTemplate(false);
    }
  };

  // 수입검사 저장 핸들러 (hooks는 early return 전에 호출해야 함)
  const handleImportSave = useCallback(async () => {
    if (!importDocRef.current) return;

    const data = importDocRef.current.getInspectionData();
    setIsSaving(true);
    try {
      // TODO: 실제 저장 API 연동
      toast.success('검사 데이터가 저장되었습니다.');
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsSaving(false);
    }
  }, []);

  if (!doc) return null;

  const docInfo = DOCUMENT_INFO[doc.type] || { label: doc.title, hasTemplate: false, color: 'text-gray-600' };
  const subtitle = documentItem
    ? `${docInfo.label} - ${documentItem.date}${documentItem.code ? ` 로트: ${documentItem.code}` : ''}`
    : docInfo.label;

  // 품질관리서 PDF 업로드 핸들러
  const handleQualityFileUpload = (file: File) => {
  };

  const handleQualityFileDelete = () => {
  };

  // 작업일지 공정별 렌더링
  const renderWorkLogDocument = () => {
    const subType = documentItem?.subType;
    const mockOrder = createQmsMockWorkOrder(subType);

    switch (subType) {
      case 'screen':
        return <ScreenWorkLogContent data={mockOrder} />;
      case 'slat':
        return <SlatWorkLogContent data={mockOrder} />;
      case 'bending':
        return <BendingWorkLogContent data={mockOrder} />;
      default:
        // subType 미지정 시 스크린 기본
        return <ScreenWorkLogContent data={mockOrder} />;
    }
  };

  // 중간검사 성적서 서브타입에 따른 렌더링 (신규 버전 통일)
  const renderReportDocument = () => {
    const subType = documentItem?.subType;
    const mockOrder = createQmsMockWorkOrder(subType || 'screen');
    switch (subType) {
      case 'screen':
        return <ScreenInspectionContent data={mockOrder} readOnly />;
      case 'bending':
        return <BendingInspectionContent data={mockOrder} readOnly />;
      case 'slat':
        return <SlatInspectionContent data={mockOrder} readOnly />;
      case 'jointbar':
        return <JointbarInspectionDocument />;
      default:
        return <ScreenInspectionContent data={mockOrder} readOnly />;
    }
  };

  // 수입검사 문서 렌더링 (Lazy Loading)
  const renderImportInspectionDocument = () => {
    if (isLoadingTemplate) {
      return <LoadingDocument />;
    }

    if (templateError) {
      return <ErrorDocument message={templateError} onRetry={loadInspectionTemplate} />;
    }

    // 템플릿이 로드되면 전달, 아니면 기본 템플릿 사용
    return (
      <ImportInspectionDocument
        ref={importDocRef}
        template={importTemplate || undefined}
        initialValues={importInitialValues}
        readOnly={readOnly}
        inspectorDept={inspectorDept}
      />
    );
  };

  // 문서 타입에 따른 컨텐츠 렌더링
  const renderDocumentContent = () => {
    switch (doc.type) {
      case 'order':
        return (
          <SalesOrderDocument
            orderNumber="KD-SS-240924-19"
            documentNumber="KD-SS-240924-19"
            certificationNumber="KD-SS-240924-19"
            orderDate="2024-09-24"
            client="삼성물산(주)"
            siteName="강남 아파트 단지"
            manager="김담당"
            managerContact="010-1234-5678"
            deliveryRequestDate="2024-10-05"
            expectedShipDate="2024-10-04"
            deliveryMethod="직접배차"
            address="서울시 강남구 테헤란로 123"
            recipientName="김인수"
            recipientContact="010-9876-5432"
            shutterCount={8}
            products={QMS_MOCK_PRODUCTS}
            items={QMS_MOCK_ORDER_ITEMS}
            remarks="납기일 엄수 요청"
          />
        );
      case 'log':
        return renderWorkLogDocument();
      case 'confirmation':
        return <DeliveryConfirmation data={MOCK_SHIPMENT_DETAIL} />;
      case 'shipping':
        return <ShippingSlip data={MOCK_SHIPMENT_DETAIL} />;
      case 'import':
        return renderImportInspectionDocument();
      case 'product':
        return <InspectionReportDocument data={QMS_MOCK_REPORT_DATA} />;
      case 'report':
        return renderReportDocument();
      case 'quality':
        return (
          <QualityDocumentUploader
            onFileUpload={handleQualityFileUpload}
            onFileDelete={handleQualityFileDelete}
            disabled={readOnly}
          />
        );
      default:
        return <PlaceholderDocument docType={doc.type} docItem={documentItem} />;
    }
  };

  // 다운로드 핸들러 (TODO: 실제 구현)
  const handleDownload = () => {
  };

  // 수입검사 저장 버튼 (toolbarExtra) - readOnly일 때 숨김
  const importToolbarExtra = doc.type === 'import' && !readOnly ? (
    <Button onClick={handleImportSave} disabled={isSaving} size="sm">
      {isSaving ? (
        <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />
      ) : (
        <Save className="w-4 h-4 mr-1.5" />
      )}
      {isSaving ? '저장 중...' : '저장'}
    </Button>
  ) : undefined;

  return (
    <DocumentViewer
      title={doc.title}
      subtitle={subtitle}
      preset="inspection"
      open={isOpen}
      onOpenChange={(open) => !open && onClose()}
      onDownload={handleDownload}
      toolbarExtra={importToolbarExtra}
    >
      {renderDocumentContent()}
    </DocumentViewer>
  );
};
