"use client";

/**
 * InspectionModal (QMS 전용)
 *
 * 수입검사, 수주서, 납품확인서, 출고증, 품질관리서 등
 * 아직 독립 모달이 없는 문서 타입만 처리.
 *
 * 작업일지(log), 중간검사(report), 제품검사(product)는
 * 각각 WorkLogModal, InspectionReportModal, ProductInspectionViewModal로 분리됨.
 */

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 { getDocumentDetail } from '../actions';

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

// 수주서 문서 컴포넌트 import
import { SalesOrderDocument } from '@/components/orders/documents/SalesOrderDocument';
import { getOrderDocumentDetail } from '@/components/orders/actions';
import type { OrderDocumentDetail } from '@/components/outbound/ShipmentManagement/documents/ShipmentOrderDocument';

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

import type { ImportInspectionTemplate, ImportInspectionRef, InspectionItemValue } from './documents/ImportInspectionDocument';

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

/**
 * 저장된 document.data (field_key 기반)를 ImportInspectionDocument의 initialValues로 변환
 *
 * 두 가지 저장 형식을 모두 지원:
 * - 정규화 형식: section_id + row_index로 항목 식별, field_key는 "n1", "n1_ok" 등
 * - 레거시 형식: field_key에 item.id 포함, 예: "${itemId}_n1", "${itemId}_okng_n1"
 */
function parseSavedDataToInitialValues(
  tmpl: ImportInspectionTemplate,
  docData: Array<{ field_key: string; field_value: string | null; section_id?: number | null; row_index?: number }>,
  sections?: Array<{ id: number; items: Array<{ id: number }> }>
): InspectionItemValue[] {
  // (sectionId, rowIndex) → inspectionItem.id 역매핑 구축
  const reverseMap = new Map<string, string>();
  if (sections) {
    for (const section of sections) {
      section.items.forEach((sItem, idx) => {
        reverseMap.set(`${section.id}_${idx}`, String(sItem.id));
      });
    }
  }

  // 정규화 형식: itemId → { field_key → value }
  const normalizedMap = new Map<string, Map<string, string>>();
  // 레거시 형식: "${itemId}_n1" → value
  const legacyMap = new Map<string, string>();

  for (const d of docData) {
    if (!d.field_value) continue;
    const key = d.field_key;
    const val = d.field_value;

    // 전역 필드는 스킵
    if (key === 'overall_result' || key === 'footer_judgement') continue;
    if (key === 'remark' || key === 'footer_remark') continue;

    // 정규화 형식: section_id가 있으면 역매핑으로 item 찾기
    if (d.section_id != null && reverseMap.size > 0) {
      const itemId = reverseMap.get(`${d.section_id}_${d.row_index ?? 0}`);
      if (itemId) {
        if (!normalizedMap.has(itemId)) normalizedMap.set(itemId, new Map());
        normalizedMap.get(itemId)!.set(key, val);
      }
      continue;
    }

    // 레거시 형식 fallback
    legacyMap.set(key, val);
  }

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

    // 정규화 형식 우선 시도
    const nData = normalizedMap.get(item.id);
    if (nData && nData.size > 0) {
      for (let n = 0; n < item.measurementCount; n++) {
        if (isOkng) {
          const okVal = nData.get(`n${n + 1}_ok`);
          const ngVal = nData.get(`n${n + 1}_ng`);
          if (okVal === 'OK') measurements[n] = 'OK';
          else if (ngVal === 'NG') measurements[n] = 'NG';
        } else {
          const val = nData.get(`n${n + 1}`);
          if (val) {
            const num = parseFloat(val);
            measurements[n] = isNaN(num) ? null : num;
          }
        }
      }

      const resultVal = nData.get('value');
      let result: 'OK' | 'NG' | null = null;
      if (resultVal === '적합' || resultVal === 'ok') result = 'OK';
      else if (resultVal === '부적합' || resultVal === 'ng') result = 'NG';

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

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

    const resultVal = legacyMap.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;
  itemName?: string;
  specification?: string;
  supplier?: string;
  inspector?: string;
  inspectorDept?: string;
  lotSize?: number;
  materialNo?: string;
  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' },
  confirmation: { label: '납품확인서', hasTemplate: true, color: 'text-red-500' },
  shipping: { label: '출고증', hasTemplate: true, color: 'text-gray-600' },
  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>
  );
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type DocumentDetailData = Record<string, any>;

/**
 * API 출고 상세 응답 → ShipmentDetail 타입 매핑
 * 헤더 정보 매핑 (BOM 데이터는 orderDetail props로 별도 전달)
 */
function mapShipmentApiToDetail(api: DocumentDetailData): ShipmentDetail {
  return {
    id: String(api.id || ''),
    shipmentNo: api.shipment_no || '-',
    lotNo: api.lot_no || '-',
    siteName: api.site_name || '-',
    customerName: api.customer_name || '-',
    customerGrade: api.customer_grade || '-',
    status: api.status || 'scheduled',
    scheduledDate: api.scheduled_date || '-',
    deliveryMethod: api.delivery_method || 'loading',
    freightCost: api.shipping_cost,
    receiver: api.receiver,
    receiverContact: api.receiver_contact,
    deliveryAddress: api.delivery_address || '-',
    vehicleNo: api.vehicle_no,
    driverName: api.driver_name,
    driverContact: api.driver_contact,
    remarks: api.remarks,
    vehicleDispatches: (api.vehicle_dispatches || []).map((d: DocumentDetailData, i: number) => ({
      id: String(i),
      logisticsCompany: d.logistics_company || '-',
      arrivalDateTime: d.arrival_datetime || '-',
      tonnage: d.tonnage || '-',
      vehicleNo: d.vehicle_no || '-',
      driverContact: d.driver_contact || '-',
      remarks: d.remarks || '',
    })),
    // Phase 2: product_groups/other_parts 실 데이터 매핑 예정
    productGroups: [],
    otherParts: [],
    // 하위 호환 필드 (최소값)
    products: [],
    priority: 'normal',
    depositConfirmed: false,
    invoiceIssued: false,
    canShip: false,
  } as ShipmentDetail;
}

// 로딩 컴포넌트
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
 * - 수입검사, 수주서, 납품확인서, 출고증, 품질관리서만 처리
 * - 작업일지/중간검사/제품검사는 각각 독립 모달로 분리됨
 */
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);

  // 수주서/출고증/납품확인서 실 데이터 상태
  const [docDetailData, setDocDetailData] = useState<DocumentDetailData | null>(null);
  const [isLoadingDocDetail, setIsLoadingDocDetail] = useState(false);

  // 출고증/납품확인서용 수주 BOM 데이터 (orderDetail)
  const [shipmentOrderDetail, setShipmentOrderDetail] = useState<OrderDocumentDetail | null>(null);

  // 수주서/출고증/납품확인서 데이터 로드
  useEffect(() => {
    if (!isOpen || !doc) return;
    if (!['order', 'confirmation', 'shipping'].includes(doc.type)) return;

    const docItemId = documentItem?.id || doc.id;
    if (!docItemId) return;

    setIsLoadingDocDetail(true);
    setShipmentOrderDetail(null);

    getDocumentDetail(doc.type, docItemId)
      .then(async (result) => {
        if (result.success && result.data) {
          const raw = result.data as DocumentDetailData;
          const detailData = raw?.data ?? raw;
          setDocDetailData(detailData);

          // 출고증/납품확인서: 수주 BOM 데이터 추가 로드
          if (['confirmation', 'shipping'].includes(doc.type) && detailData) {
            // shipment API 응답에서 order_id를 찾아 BOM 조회
            const shipmentData = detailData as DocumentDetailData;
            const orderId = shipmentData.order_id;
            if (orderId) {
              const bomResult = await getOrderDocumentDetail(String(orderId));
              if (bomResult.success && bomResult.data) {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const bomRaw = bomResult.data as Record<string, any>;
                setShipmentOrderDetail((bomRaw?.data ?? bomRaw) as OrderDocumentDetail);
              }
            }
          }
        }
      })
      .finally(() => setIsLoadingDocDetail(false));

    return () => {
      setDocDetailData(null);
      setShipmentOrderDetail(null);
    };
  }, [isOpen, doc?.type, doc?.id, documentItem?.id]);

  // 수입검사 템플릿 로드 (모달 열릴 때)
  useEffect(() => {
    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 () => {
    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);

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

  // 수입검사 저장 핸들러
  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 = () => {
  };

  // 수입검사 문서 렌더링 (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': {
        if (isLoadingDocDetail) return <LoadingDocument />;
        if (!docDetailData) return <ErrorDocument message="수주서 데이터를 불러올 수 없습니다." />;
        const d = docDetailData;
        return (
          <SalesOrderDocument
            orderNumber={d.order_no || '-'}
            documentNumber={d.order_no || '-'}
            certificationNumber={d.order_no || '-'}
            orderDate={d.received_at || '-'}
            client={d.client_name || '-'}
            siteName={d.site_name || '-'}
            manager={d.manager_name || '-'}
            managerContact={d.client_contact || '-'}
            deliveryRequestDate={d.delivery_date || '-'}
            deliveryMethod={d.delivery_method_code || '-'}
            address={[d.shipping_address, d.shipping_address_detail].filter(Boolean).join(' ') || '-'}
            recipientName={d.receiver || '-'}
            recipientContact={d.receiver_contact || '-'}
            shutterCount={d.nodes_count || 0}
            remarks={d.remarks}
            productRows={d.products || []}
            motorsLeft={d.motors?.left || []}
            motorsRight={d.motors?.right || []}
            bendingParts={d.bending_parts || []}
            subsidiaryParts={d.subsidiary_parts || []}
            categoryCode={d.category_code}
          />
        );
      }
      case 'confirmation':
      case 'shipping':
        if (isLoadingDocDetail) return <LoadingDocument />;
        if (!docDetailData) return <ErrorDocument message="출고 데이터를 불러올 수 없습니다." />;
        return doc.type === 'confirmation'
          ? <DeliveryConfirmation data={mapShipmentApiToDetail(docDetailData)} orderDetail={shipmentOrderDetail} />
          : <ShippingSlip data={mapShipmentApiToDetail(docDetailData)} orderDetail={shipmentOrderDetail} />;
      case 'import':
        return renderImportInspectionDocument();
      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>
  );
};