'use client';

/**
 * 제품검사 상세/수정 페이지
 *
 * 기획서 기반 전면 재구축:
 * - 기본정보, 건축공사장, 자재유통업자, 공사시공자, 공사감리자 정보
 * - 검사 정보 (검사방문요청일, 기간, 검사자, 현장주소)
 * - 수주 설정 정보 (규격 비교 테이블, 요약)
 * - 헤더 액션 (검사제품요청서 보기, 제품검사하기, 검사 완료)
 */

import { useState, useCallback, useEffect, useMemo } from 'react';
import dynamic from 'next/dynamic';
import { useRouter, useSearchParams } from 'next/navigation';
import { useDaumPostcode } from '@/hooks/useDaumPostcode';
import {
  FileText,
  PlayCircle,
  CheckCircle2,
  Loader2,
  Plus,
  Trash2,
  ClipboardCheck,
  Pencil,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
} from '@/components/ui/accordion';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { inspectionConfig } from './inspectionConfig';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { toast } from 'sonner';
import {
  getInspectionById,
  updateInspection,
  completeInspection,
  saveLocationInspection,
} from './actions';
import { getFqcStatus, type FqcStatusItem } from './fqcActions';
import {
  statusColorMap,
  calculateOrderSummary,
  buildRequestDocumentData,
  buildReportDocumentData,
} from './mockData';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

const InspectionRequestModal = dynamic(
  () => import('./documents/InspectionRequestModal').then(mod => ({ default: mod.InspectionRequestModal })),
);
const InspectionReportModal = dynamic(
  () => import('./documents/InspectionReportModal').then(mod => ({ default: mod.InspectionReportModal })),
);
const ProductInspectionInputModal = dynamic(
  () => import('./ProductInspectionInputModal').then(mod => ({ default: mod.ProductInspectionInputModal })),
);
const OrderSelectModal = dynamic(
  () => import('./OrderSelectModal').then(mod => ({ default: mod.OrderSelectModal })),
);
const SupplierSearchModal = dynamic(
  () => import('@/components/material/ReceivingManagement/SupplierSearchModal').then(mod => ({ default: mod.SupplierSearchModal })),
);
import type {
  ProductInspection,
  InspectionFormData,
  OrderSettingItem,
  OrderSelectItem,
  OrderGroup,
  ProductInspectionData,
} from './types';

interface InspectionDetailProps {
  id: string;
}

// 폼 초기값
const EMPTY_FORM: InspectionFormData = {
  qualityDocNumber: '',
  siteName: '',
  client: '',
  manager: '',
  managerContact: '',
  constructionSite: { siteName: '', landLocation: '', lotNumber: '' },
  materialDistributor: { companyName: '', companyAddress: '', representativeName: '', phone: '' },
  constructorInfo: { companyName: '', companyAddress: '', name: '', phone: '' },
  supervisor: { officeName: '', officeAddress: '', name: '', phone: '' },
  scheduleInfo: {
    visitRequestDate: '',
    startDate: '',
    endDate: '',
    inspector: '',
    sitePostalCode: '',
    siteAddress: '',
    siteAddressDetail: '',
  },
  orderItems: [],
};

export function InspectionDetail({ id }: InspectionDetailProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const isEditModeParam = searchParams.get('mode') === 'edit';

  // Daum 우편번호 서비스
  const { openPostcode } = useDaumPostcode({
    onComplete: (result) => {
      setFormData(prev => ({
        ...prev,
        scheduleInfo: {
          ...prev.scheduleInfo,
          sitePostalCode: result.zonecode,
          siteAddress: result.address,
        },
      }));
    },
  });

  // 상세 데이터
  const [inspection, setInspection] = useState<ProductInspection | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 완료 상태면 편집 모드 강제 해제
  const isEditMode = isEditModeParam && inspection?.status !== '완료';

  // 수정 폼 데이터
  const [formData, setFormData] = useState<InspectionFormData>(EMPTY_FORM);

  // 검사 완료 다이얼로그
  const [showCompleteDialog, setShowCompleteDialog] = useState(false);
  const [isCompleting, setIsCompleting] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 수주 선택 모달
  const [orderModalOpen, setOrderModalOpen] = useState(false);
  const [clientModalOpen, setClientModalOpen] = useState(false);

  // 문서 모달
  const [requestDocOpen, setRequestDocOpen] = useState(false);
  const [reportDocOpen, setReportDocOpen] = useState(false);

  // 제품검사 입력 모달
  const [inspectionInputOpen, setInspectionInputOpen] = useState(false);
  const [selectedOrderItem, setSelectedOrderItem] = useState<OrderSettingItem | null>(null);

  // FQC 상태 데이터 (개소별 진행현황)
  const [fqcStatusItems, setFqcStatusItems] = useState<FqcStatusItem[]>([]);

  // 파생: 진행현황 통계
  // 개소별 검사 상태 집계 (legacy inspectionData + FQC 통합)
  const inspectionStats = useMemo(() => {
    const items = isEditMode ? formData.orderItems : (inspection?.orderItems || []);
    if (items.length === 0) return null;

    const getStatus = (item: OrderSettingItem) => {
      // FQC 문서 기반 상태 확인
      const fqcItem = fqcStatusItems.find(
        (i) => i.floorCode === item.floor && i.symbolCode === item.symbol
      );
      if (fqcItem?.judgement === '합격') return 'passed';
      if (fqcItem?.judgement === '불합격') return 'failed';
      if (fqcItem?.documentId) return 'inProgress';

      // legacy inspectionData 확인
      if (!item.inspectionData) return 'none';
      const d = item.inspectionData;
      const judgmentFields = [
        d.appearanceProcessing, d.appearanceSewing, d.appearanceAssembly,
        d.appearanceSmokeBarrier, d.appearanceBottomFinish, d.motor, d.material,
        d.lengthJudgment, d.heightJudgment, d.guideRailGap, d.bottomFinishGap,
        d.fireResistanceTest, d.smokeLeakageTest, d.openCloseTest, d.impactTest,
      ];
      const inspected = judgmentFields.filter(v => v !== null && v !== undefined);
      const hasPhotos = d.productImages && d.productImages.length > 0;
      if (inspected.length === 0 && !hasPhotos) return 'none';
      if (inspected.length < judgmentFields.length || !hasPhotos) return 'inProgress';
      if (inspected.some(v => v === 'fail')) return 'failed';
      return 'passed';
    };

    const statuses = items.map(getStatus);
    return {
      total: items.length,
      passed: statuses.filter(s => s === 'passed').length,
      failed: statuses.filter(s => s === 'failed').length,
      inProgress: statuses.filter(s => s === 'inProgress').length,
      none: statuses.filter(s => s === 'none').length,
    };
  }, [isEditMode, formData.orderItems, inspection?.orderItems, fqcStatusItems]);

  // 개소별 FQC 상태 조회 헬퍼 (floor+symbol 기반 매칭)
  const getFqcItemStatus = useCallback(
    (item: OrderSettingItem): FqcStatusItem | null => {
      return fqcStatusItems.find(
        (i) => i.floorCode === item.floor && i.symbolCode === item.symbol
      ) ?? null;
    },
    [fqcStatusItems]
  );

  // ===== API 데이터 로드 =====
  const loadInspection = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await getInspectionById(id);
      if (result.success && result.data) {
        setInspection(result.data);
        // Edit 모드용 폼 데이터 초기화
        setFormData({
          qualityDocNumber: result.data.qualityDocNumber,
          siteName: result.data.siteName,
          client: result.data.client,
          clientId: result.data.clientId,
          manager: result.data.manager,
          managerContact: result.data.managerContact,
          constructionSite: { ...result.data.constructionSite },
          materialDistributor: { ...result.data.materialDistributor },
          constructorInfo: { ...result.data.constructorInfo },
          supervisor: { ...result.data.supervisor },
          scheduleInfo: { ...result.data.scheduleInfo },
          orderItems: result.data.orderItems.map((item) => ({ ...item })),
        });
      } else {
        toast.error(result.error || '제품검사 데이터를 불러오는데 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[InspectionDetail] loadInspection error:', error);
      toast.error('데이터 로드 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [id]);

  useEffect(() => {
    loadInspection();
  }, [loadInspection]);

  // ===== FQC 진행현황 로드 =====
  useEffect(() => {
    if (!inspection) return;

    // orderItems에서 고유 orderId 추출 (API에서 제공되는 경우만)
    const orderIds = new Set<number>();
    inspection.orderItems.forEach((item) => {
      if (item.orderId) orderIds.add(item.orderId);
    });

    if (orderIds.size === 0) return; // orderId 없으면 legacy 모드 유지

    // 각 orderId별 FQC 상태 조회
    const loadFqcStatus = async () => {
      const allItems: FqcStatusItem[] = [];
      for (const orderId of orderIds) {
        const result = await getFqcStatus(orderId);
        if (result.success && result.data) {
          allItems.push(...result.data.items);
        }
      }
      if (allItems.length > 0) {
        setFqcStatusItems(allItems);
      }
    };

    loadFqcStatus();
  }, [inspection]);

  // ===== 네비게이션 =====
  const handleEdit = useCallback(() => {
    router.push(`/quality/inspections/${id}?mode=edit`);
  }, [id, router]);

  // ===== 검사 완료 처리 =====
  const handleComplete = useCallback(async () => {
    setIsCompleting(true);
    try {
      const result = await completeInspection(id);
      if (result.success) {
        toast.success('검사가 완료 처리되었습니다.');
        setShowCompleteDialog(false);
        router.push('/quality/inspections');
      } else {
        toast.error(result.error || '검사 완료 처리에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      toast.error('검사 완료 처리 중 오류가 발생했습니다.');
    } finally {
      setIsCompleting(false);
    }
  }, [id, router]);

  // ===== 수정 제출 =====
  const handleSubmit = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
    setIsSubmitting(true);
    try {
      const result = await updateInspection(id, formData);
      if (result.success) {
        toast.success('제품검사가 수정되었습니다.');
        router.push(`/quality/inspections/${id}?mode=view`);
        return { success: true };
      }
      return { success: false, error: result.error || '수정에 실패했습니다.' };
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      return { success: false, error: '수정 중 오류가 발생했습니다.' };
    } finally {
      setIsSubmitting(false);
    }
  }, [id, formData, router]);

  // ===== 폼 필드 변경 헬퍼 =====
  const updateField = useCallback(<K extends keyof InspectionFormData>(
    key: K,
    value: InspectionFormData[K]
  ) => {
    setFormData((prev) => ({ ...prev, [key]: value }));
  }, []);

  const updateNested = useCallback((
    section: 'constructionSite' | 'materialDistributor' | 'constructorInfo' | 'supervisor' | 'scheduleInfo',
    field: string,
    value: string
  ) => {
    setFormData((prev) => ({
      ...prev,
      [section]: {
        ...(prev[section] as unknown as Record<string, unknown>),
        [field]: value,
      },
    }));
  }, []);

  // ===== 수주 선택/삭제 처리 =====
  const handleOrderSelect = useCallback((items: OrderSelectItem[]) => {
    const newOrderItems: OrderSettingItem[] = items.flatMap((item) =>
      item.locations.length > 0
        ? item.locations.map((loc) => ({
            id: `${item.id}-${loc.nodeId}`,
            orderId: Number(item.id),
            orderNumber: item.orderNumber,
            siteName: item.siteName,
            clientId: item.clientId,
            clientName: item.clientName,
            itemId: item.itemId,
            itemName: item.itemName,
            deliveryDate: item.deliveryDate,
            floor: loc.floor,
            symbol: loc.symbol,
            orderWidth: loc.orderWidth,
            orderHeight: loc.orderHeight,
            constructionWidth: 0,
            constructionHeight: 0,
            changeReason: '',
          }))
        : [{
            id: item.id,
            orderId: Number(item.id),
            orderNumber: item.orderNumber,
            siteName: item.siteName,
            clientId: item.clientId,
            clientName: item.clientName,
            itemId: item.itemId,
            itemName: item.itemName,
            deliveryDate: item.deliveryDate,
            floor: '',
            symbol: '',
            orderWidth: 0,
            orderHeight: 0,
            constructionWidth: 0,
            constructionHeight: 0,
            changeReason: '',
          }]
    );
    setFormData((prev) => {
      const updated = { ...prev, orderItems: [...prev.orderItems, ...newOrderItems] };
      // 수주처 미선택 상태에서 수주 선택 시 → 수주처 자동 채움
      if (!prev.clientId && items.length > 0 && items[0].clientId) {
        updated.clientId = items[0].clientId ?? undefined;
        updated.client = items[0].clientName || '';
      }
      return updated;
    });
  }, []);

  const handleRemoveOrderItem = useCallback((itemId: string) => {
    setFormData((prev) => ({
      ...prev,
      orderItems: prev.orderItems.filter((item) => item.id !== itemId),
    }));
  }, []);

  // 이미 선택된 수주 ID 목록 (orderId 기준, 중복 제거)
  const excludeOrderIds = useMemo(
    () => [...new Set(formData.orderItems.map((item) => String(item.orderId ?? item.id)))],
    [formData.orderItems]
  );

  // 수주 선택 필터: 기본정보 수주처 또는 이미 선택된 수주 기준
  const orderFilter = useMemo(() => {
    const items = isEditMode ? formData.orderItems : (inspection?.orderItems || []);
    // 기본정보에서 수주처가 선택된 경우 → 해당 거래처 필터
    if (formData.clientId) {
      const firstItem = items[0];
      return {
        clientId: formData.clientId,
        itemId: firstItem?.itemId ?? undefined,
        label: [formData.client, firstItem?.itemName].filter(Boolean).join(' / ') || undefined,
      };
    }
    // 수주가 선택된 경우 → 첫 수주 기준 필터
    if (items.length > 0) {
      const first = items[0];
      return {
        clientId: first.clientId ?? undefined,
        itemId: first.itemId ?? undefined,
        label: [first.clientName, first.itemName].filter(Boolean).join(' / ') || undefined,
      };
    }
    return { clientId: undefined, itemId: undefined, label: undefined };
  }, [isEditMode, formData.clientId, formData.client, formData.orderItems, inspection?.orderItems]);

  // ===== 수주 설정 요약 =====
  const orderSummary = useMemo(() => {
    const items = isEditMode ? formData.orderItems : (inspection?.orderItems || []);
    return calculateOrderSummary(items);
  }, [isEditMode, formData.orderItems, inspection?.orderItems]);

  // ===== 수주 항목을 그룹별로 묶기 (아코디언용) =====
  const groupOrderItems = useCallback((items: OrderSettingItem[]): OrderGroup[] => {
    const groups: Record<string, OrderGroup> = {};
    items.forEach((item) => {
      const key = item.orderNumber;
      if (!groups[key]) {
        groups[key] = {
          orderNumber: item.orderNumber,
          siteName: item.siteName,
          deliveryDate: item.deliveryDate,
          locationCount: 0,
          items: [],
        };
      }
      groups[key].items.push(item);
      groups[key].locationCount = groups[key].items.length;
    });
    return Object.values(groups);
  }, []);

  const orderGroups = useMemo(() => {
    const items = isEditMode ? formData.orderItems : (inspection?.orderItems || []);
    return groupOrderItems(items);
  }, [isEditMode, formData.orderItems, inspection?.orderItems, groupOrderItems]);

  // ===== 제품검사 입력 핸들러 =====
  const handleOpenInspectionInput = useCallback((item: OrderSettingItem) => {
    setSelectedOrderItem(item);
    setInspectionInputOpen(true);
  }, []);

  const handleInspectionComplete = useCallback(async (
    data: ProductInspectionData,
    constructionInfo?: { width: number | null; height: number | null; changeReason: string }
  ) => {
    if (!selectedOrderItem) return;

    // 서버에 개소별 검사 데이터 저장
    const result = await saveLocationInspection(id, selectedOrderItem.id, data, constructionInfo);
    if (!result.success) {
      toast.error(result.error || '검사 데이터 저장에 실패했습니다.');
      return;
    }

    const updateItem = (item: OrderSettingItem) => {
      if (item.id !== selectedOrderItem.id) return item;
      const updated = { ...item, inspectionData: data };
      if (constructionInfo) {
        if (constructionInfo.width !== null) updated.constructionWidth = constructionInfo.width;
        if (constructionInfo.height !== null) updated.constructionHeight = constructionInfo.height;
        updated.changeReason = constructionInfo.changeReason;
      }
      return updated;
    };

    // 로컬 state도 반영
    setFormData((prev) => ({
      ...prev,
      orderItems: prev.orderItems.map(updateItem),
    }));

    // inspection 데이터도 갱신 (새로고침 없이 반영)
    if (inspection) {
      setInspection({
        ...inspection,
        orderItems: inspection.orderItems.map(updateItem),
      });
    }

    toast.success('검사 데이터가 저장되었습니다.');
  }, [id, selectedOrderItem, inspection]);

  // ===== 시공규격/변경사유 수정 핸들러 (수정 모드) =====
  const handleUpdateOrderItemField = useCallback((
    itemId: string,
    field: 'constructionWidth' | 'constructionHeight' | 'changeReason',
    value: string | number
  ) => {
    setFormData((prev) => ({
      ...prev,
      orderItems: prev.orderItems.map((item) =>
        item.id === itemId ? { ...item, [field]: value } : item
      ),
    }));
  }, []);

  // ===== FQC 상태 뱃지 렌더링 =====
  const renderFqcBadge = useCallback(
    (item: OrderSettingItem) => {
      const fqcItem = getFqcItemStatus(item);
      if (!fqcItem) {
        // FQC 데이터 없음 → legacy 상태
        return item.inspectionData ? (
          <Badge className="bg-green-100 text-green-800 border-0">검사완료</Badge>
        ) : (
          <Badge variant="outline" className="text-muted-foreground min-w-[3.5rem] justify-center">미검사</Badge>
        );
      }
      if (fqcItem.judgement === '합격') {
        return <Badge className="bg-green-100 text-green-800 border-0 min-w-[3.5rem] justify-center">합격</Badge>;
      }
      if (fqcItem.judgement === '불합격') {
        return <Badge className="bg-red-100 text-red-800 border-0 min-w-[3.5rem] justify-center">불합격</Badge>;
      }
      if (fqcItem.documentId) {
        return <Badge className="bg-blue-100 text-blue-800 border-0 min-w-[3.5rem] justify-center">진행중</Badge>;
      }
      // FQC 문서 없음 → legacy 검사 데이터 확인
      if (!item.inspectionData) {
        return <Badge variant="outline" className="text-muted-foreground min-w-[3.5rem] justify-center">미검사</Badge>;
      }
      const d = item.inspectionData;
      const judgmentFields = [
        d.appearanceProcessing, d.appearanceSewing, d.appearanceAssembly,
        d.appearanceSmokeBarrier, d.appearanceBottomFinish, d.motor, d.material,
        d.lengthJudgment, d.heightJudgment, d.guideRailGap, d.bottomFinishGap,
        d.fireResistanceTest, d.smokeLeakageTest, d.openCloseTest, d.impactTest,
      ];
      const inspected = judgmentFields.filter(v => v !== null && v !== undefined);
      const hasPhotos = d.productImages && d.productImages.length > 0;
      if (inspected.length === 0 && !hasPhotos) {
        return <Badge variant="outline" className="text-muted-foreground min-w-[3.5rem] justify-center">미검사</Badge>;
      }
      if (inspected.length < judgmentFields.length || !hasPhotos) {
        return <Badge className="bg-blue-100 text-blue-800 border-0 min-w-[3.5rem] justify-center">진행중</Badge>;
      }
      if (inspected.some(v => v === 'fail')) {
        return <Badge className="bg-red-100 text-red-800 border-0 min-w-[3.5rem] justify-center">불합격</Badge>;
      }
      return <Badge className="bg-green-100 text-green-800 border-0 min-w-[3.5rem] justify-center">합격</Badge>;
    },
    [getFqcItemStatus]
  );

  // ===== 정보 필드 렌더링 헬퍼 =====
  const renderInfoField = (label: string, value: React.ReactNode) => (
    <div>
      <div className="text-sm text-muted-foreground mb-1">{label}</div>
      <div className="font-medium">{value || '-'}</div>
    </div>
  );

  // ===== FQC 진행현황 통계 바 =====
  const renderFqcProgressBar = useMemo(() => {
    if (!inspectionStats) return null;
    const { total, passed, failed, inProgress, none } = inspectionStats;
    return (
      <div className="space-y-2">
        <div className="flex items-center gap-4 text-xs">
          <span className="text-green-600 font-medium">합격 {passed}</span>
          <span className="text-red-600 font-medium">불합격 {failed}</span>
          <span className="text-blue-600 font-medium">진행중 {inProgress}</span>
          <span className="text-muted-foreground">미검사 {none}</span>
        </div>
        <div className="w-full h-2 bg-gray-200 rounded-full overflow-hidden flex">
          {passed > 0 && (
            <div
              className="h-full bg-green-500"
              style={{ width: `${(passed / total) * 100}%` }}
            />
          )}
          {failed > 0 && (
            <div
              className="h-full bg-red-500"
              style={{ width: `${(failed / total) * 100}%` }}
            />
          )}
          {inProgress > 0 && (
            <div
              className="h-full bg-blue-400"
              style={{ width: `${(inProgress / total) * 100}%` }}
            />
          )}
        </div>
      </div>
    );
  }, [inspectionStats]);

  // ===== 수주 설정 아코디언 (조회 모드) =====
  const renderOrderAccordion = (groups: OrderGroup[]) => {
    if (groups.length === 0) {
      return (
        <div className="text-center text-muted-foreground py-8">
          수주 설정 정보가 없습니다.
        </div>
      );
    }

    return (
      <div className="space-y-4">
        {groups.map((group, _groupIndex) => (
          <div key={group.orderNumber} className="border rounded-lg">
            <div className="flex items-center gap-6 text-sm px-4 py-3 bg-muted/30 rounded-t-lg">
              <span className="font-medium w-32">{group.orderNumber}</span>
              <span className="text-muted-foreground flex-1">{group.siteName}</span>
              <span className="text-muted-foreground w-28">{group.deliveryDate}</span>
              <span className="text-muted-foreground w-16">{group.locationCount}개소</span>
            </div>
            <div className="px-4 pb-4">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12 text-center">No.</TableHead>
                    <TableHead>층수</TableHead>
                    <TableHead>부호</TableHead>
                    <TableHead className="text-center">수주 가로</TableHead>
                    <TableHead className="text-center">수주 세로</TableHead>
                    <TableHead className="text-center">시공 가로</TableHead>
                    <TableHead className="text-center">시공 세로</TableHead>
                    <TableHead>변경사유</TableHead>
                    <TableHead className="w-32 text-center">검사</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {group.items.map((item, index) => (
                    <TableRow key={item.id}>
                      <TableCell className="text-center">{index + 1}</TableCell>
                      <TableCell>{item.floor || '-'}</TableCell>
                      <TableCell>{item.symbol || '-'}</TableCell>
                      <TableCell className="text-center">{item.orderWidth}</TableCell>
                      <TableCell className="text-center">{item.orderHeight}</TableCell>
                      <TableCell className="text-center">{item.constructionWidth}</TableCell>
                      <TableCell className="text-center">{item.constructionHeight}</TableCell>
                      <TableCell>{item.changeReason || '-'}</TableCell>
                      <TableCell className="text-center">
                        <div className="flex items-center justify-center gap-1.5">
                          {renderFqcBadge(item)}
                          {(getFqcItemStatus(item) || item.inspectionData) && (
                            <Badge
                              variant="outline"
                              className="cursor-pointer hover:bg-muted"
                              onClick={() => handleOpenInspectionInput(item)}
                            >
                              보기
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>
        ))}
      </div>
    );
  };

  // ===== 수주 설정 아코디언 (편집 모드 - 삭제, 시공규격/변경사유 수정 가능) =====
  const renderEditOrderAccordion = (groups: OrderGroup[]) => {
    if (groups.length === 0) {
      return (
        <div className="text-center text-muted-foreground py-8">
          수주를 선택해주세요.
        </div>
      );
    }

    return (
      <div className="space-y-4">
        {groups.map((group, _groupIndex) => (
          <div key={group.orderNumber} className="border rounded-lg">
            <div className="flex items-center gap-6 text-sm px-4 py-3 bg-muted/30 rounded-t-lg">
              <span className="font-medium w-32">{group.orderNumber}</span>
              <span className="text-muted-foreground flex-1">{group.siteName}</span>
              <span className="text-muted-foreground w-28">{group.deliveryDate}</span>
              <span className="text-muted-foreground w-16">{group.locationCount}개소</span>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7 text-muted-foreground hover:text-red-600"
                type="button"
                onClick={() => {
                  group.items.forEach((item) => handleRemoveOrderItem(item.id));
                }}
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>
            <div className="px-4 pb-4">
              {/* 하위 레벨: 테이블 (시공규격, 변경사유 편집 가능) */}
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12 text-center">No.</TableHead>
                    <TableHead>층수</TableHead>
                    <TableHead>부호</TableHead>
                    <TableHead className="text-center">수주 가로</TableHead>
                    <TableHead className="text-center">수주 세로</TableHead>
                    <TableHead className="text-center w-24">시공 가로</TableHead>
                    <TableHead className="text-center w-24">시공 세로</TableHead>
                    <TableHead className="w-40">변경사유</TableHead>
                    <TableHead className="w-36 text-center">검사</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {group.items.map((item, index) => (
                    <TableRow key={item.id}>
                      <TableCell className="text-center">{index + 1}</TableCell>
                      <TableCell>{item.floor || '-'}</TableCell>
                      <TableCell>{item.symbol || '-'}</TableCell>
                      <TableCell className="text-center">{item.orderWidth}</TableCell>
                      <TableCell className="text-center">{item.orderHeight}</TableCell>
                      <TableCell className="text-center">
                        <Input
                          type="number"
                          value={item.constructionWidth || ''}
                          onChange={(e) =>
                            handleUpdateOrderItemField(item.id, 'constructionWidth', Number(e.target.value))
                          }
                          className="h-8 w-20 text-center"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input
                          type="number"
                          value={item.constructionHeight || ''}
                          onChange={(e) =>
                            handleUpdateOrderItemField(item.id, 'constructionHeight', Number(e.target.value))
                          }
                          className="h-8 w-20 text-center"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.changeReason || ''}
                          onChange={(e) =>
                            handleUpdateOrderItemField(item.id, 'changeReason', e.target.value)
                          }
                          className="h-8"
                          placeholder="변경사유 입력"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <div className="flex items-center justify-center gap-1.5">
                          {renderFqcBadge(item)}
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleOpenInspectionInput(item)}
                            className="h-7"
                          >
                            <ClipboardCheck className="w-3.5 h-3.5 mr-1" />
                            검사
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>
        ))}
      </div>
    );
  };

  // ===== 헤더 액션 버튼 (view 및 edit 모드) =====
  const headerActions = useMemo(() => {
    if (!inspection) return null;

    // Edit 모드: 검사제품요청서 보기, 제품검사하기 버튼만 표시
    if (isEditMode) {
      return (
        <>
          <Button variant="outline" size="sm" onClick={() => setRequestDocOpen(true)}>
            <FileText className="w-4 h-4 md:mr-2" />
            <span className="hidden md:inline">검사제품요청서 보기</span>
          </Button>
          <Button variant="outline" size="sm" onClick={() => setReportDocOpen(true)}>
            <PlayCircle className="w-4 h-4 md:mr-2" />
            <span className="hidden md:inline">제품검사하기</span>
          </Button>
        </>
      );
    }

    // View 모드: 검사제품요청서 보기, 제품검사하기, 수정(완료시 disabled), 검사 완료
    const isCompleted = inspection.status === '완료';
    return (
      <>
        <Button variant="outline" size="sm" onClick={() => setRequestDocOpen(true)}>
          <FileText className="w-4 h-4 md:mr-2" />
          <span className="hidden md:inline">검사제품요청서 보기</span>
        </Button>
        <Button variant="outline" size="sm" onClick={() => setReportDocOpen(true)}>
          <PlayCircle className="w-4 h-4 md:mr-2" />
          <span className="hidden md:inline">제품검사하기</span>
        </Button>
        {isCompleted && (
          <Button size="sm" disabled title="검사완료된 건은 수정할 수 없습니다.">
            <Pencil className="w-4 h-4 md:mr-2" />
            <span className="hidden md:inline">수정</span>
          </Button>
        )}
        {!isCompleted && (() => {
          const hasIncomplete = !inspectionStats || inspectionStats.none > 0 || inspectionStats.inProgress > 0;
          return (
            <Button
              size="sm"
              className="bg-green-600 hover:bg-green-700"
              disabled={hasIncomplete}
              onClick={() => setShowCompleteDialog(true)}
              title={hasIncomplete ? (!inspectionStats ? '검사 대상이 없습니다.' : `미검사 ${inspectionStats.none}건, 진행중 ${inspectionStats.inProgress}건이 남아있습니다.`) : ''}
            >
              <CheckCircle2 className="w-4 h-4 md:mr-2" />
              <span className="hidden md:inline">검사 완료</span>
            </Button>
          );
        })()}
      </>
    );
  }, [isEditMode, inspection, inspectionStats]);

  // ===== View 모드 렌더링 =====
  const renderViewContent = useCallback(() => {
    if (!inspection) return null;

    return (
      <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {renderInfoField('품질관리서 번호', inspection.qualityDocNumber)}
              {renderInfoField('현장명', inspection.siteName)}
              {renderInfoField('수주처', inspection.client)}
              {renderInfoField('접수일', inspection.receptionDate)}
              {renderInfoField('담당자', inspection.manager)}
              {renderInfoField('담당자 연락처', inspection.managerContact)}
              {renderInfoField(
                '상태',
                <Badge className={`text-xs ${statusColorMap[inspection.status]} border-0`}>
                  {inspection.status}
                </Badge>
              )}
              {renderInfoField('작성자', inspection.author)}
            </div>
          </CardContent>
        </Card>

        {/* 건축공사장 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">건축공사장 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-6">
              {renderInfoField('현장명', inspection.constructionSite.siteName)}
              {renderInfoField('대지위치', inspection.constructionSite.landLocation)}
              {renderInfoField('지번', inspection.constructionSite.lotNumber)}
            </div>
          </CardContent>
        </Card>

        {/* 자재유통업자 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">자재유통업자 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {renderInfoField('회사명', inspection.materialDistributor.companyName)}
              {renderInfoField('회사주소', inspection.materialDistributor.companyAddress)}
              {renderInfoField('대표자명', inspection.materialDistributor.representativeName)}
              {renderInfoField('전화번호', inspection.materialDistributor.phone)}
            </div>
          </CardContent>
        </Card>

        {/* 공사시공자 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">공사시공자 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {renderInfoField('회사명', inspection.constructorInfo.companyName)}
              {renderInfoField('회사주소', inspection.constructorInfo.companyAddress)}
              {renderInfoField('성명', inspection.constructorInfo.name)}
              {renderInfoField('전화번호', inspection.constructorInfo.phone)}
            </div>
          </CardContent>
        </Card>

        {/* 공사감리자 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">공사감리자 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {renderInfoField('사무소명', inspection.supervisor.officeName)}
              {renderInfoField('사무소주소', inspection.supervisor.officeAddress)}
              {renderInfoField('성명', inspection.supervisor.name)}
              {renderInfoField('전화번호', inspection.supervisor.phone)}
            </div>
          </CardContent>
        </Card>

        {/* 검사 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">검사 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {renderInfoField('검사방문요청일', inspection.scheduleInfo.visitRequestDate)}
              {renderInfoField('검사시작일', inspection.scheduleInfo.startDate)}
              {renderInfoField('검사종료일', inspection.scheduleInfo.endDate)}
              {renderInfoField('검사자', inspection.scheduleInfo.inspector)}
            </div>
            <div className="mt-4">
              <div className="text-sm text-muted-foreground mb-1">현장 주소</div>
              <div className="font-medium">
                {inspection.scheduleInfo.sitePostalCode && (
                  <span className="text-muted-foreground mr-2">[{inspection.scheduleInfo.sitePostalCode}]</span>
                )}
                {inspection.scheduleInfo.siteAddress || '-'}
                {inspection.scheduleInfo.siteAddressDetail && (
                  <span className="ml-2">{inspection.scheduleInfo.siteAddressDetail}</span>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 수주 설정 정보 */}
        <Card>
          <CardHeader className="space-y-3">
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">수주 설정 정보</CardTitle>
              <div className="flex items-center gap-3 text-sm">
                <span>전체: <strong>{orderSummary.total}</strong>건</span>
              </div>
            </div>
            {renderFqcProgressBar}
          </CardHeader>
          <CardContent className="p-4">
            {renderOrderAccordion(orderGroups)}
          </CardContent>
        </Card>
      </div>
    );
  }, [inspection, orderSummary, orderGroups, handleOpenInspectionInput, renderFqcBadge, getFqcItemStatus, renderFqcProgressBar]);

  // ===== Edit 모드 폼 렌더링 =====
  const renderFormContent = useCallback(() => {
    if (!inspection) return null;

    return (
      <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label className="text-muted-foreground">품질관리서 번호</Label>
                <Input value={formData.qualityDocNumber} disabled className="bg-muted" />
              </div>
              <div className="space-y-2">
                <Label>현장명</Label>
                <Input
                  value={formData.siteName}
                  onChange={(e) => updateField('siteName', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>수주처</Label>
                <div className="flex gap-2">
                  <Input
                    value={formData.client}
                    readOnly
                    placeholder="거래처를 선택하세요"
                    className="cursor-pointer bg-muted/30"
                    onClick={() => setClientModalOpen(true)}
                  />
                  {formData.clientId && (
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-9 w-9 shrink-0"
                      onClick={() => {
                        updateField('client', '');
                        updateField('clientId', undefined);
                      }}
                    >
                      <Trash2 className="w-4 h-4 text-muted-foreground" />
                    </Button>
                  )}
                </div>
              </div>
              <div className="space-y-2">
                <Label className="text-muted-foreground">접수일</Label>
                <Input value={inspection.receptionDate} disabled className="bg-muted" />
              </div>
              <div className="space-y-2">
                <Label>담당자</Label>
                <Input
                  value={formData.manager}
                  onChange={(e) => updateField('manager', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>담당자 연락처</Label>
                <Input
                  value={formData.managerContact}
                  onChange={(e) => updateField('managerContact', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label className="text-muted-foreground">상태</Label>
                <Input value={inspection.status} disabled className="bg-muted" />
              </div>
              <div className="space-y-2">
                <Label className="text-muted-foreground">작성자</Label>
                <Input value={inspection.author} disabled className="bg-muted" />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 건축공사장 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">건축공사장 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label>현장명</Label>
                <Input
                  value={formData.constructionSite.siteName}
                  onChange={(e) => updateNested('constructionSite', 'siteName', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>대지위치</Label>
                <Input
                  value={formData.constructionSite.landLocation}
                  onChange={(e) => updateNested('constructionSite', 'landLocation', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>지번</Label>
                <Input
                  value={formData.constructionSite.lotNumber}
                  onChange={(e) => updateNested('constructionSite', 'lotNumber', e.target.value)}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 자재유통업자 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">자재유통업자 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label>회사명</Label>
                <Input
                  value={formData.materialDistributor.companyName}
                  onChange={(e) => updateNested('materialDistributor', 'companyName', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>회사주소</Label>
                <Input
                  value={formData.materialDistributor.companyAddress}
                  onChange={(e) => updateNested('materialDistributor', 'companyAddress', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>대표자명</Label>
                <Input
                  value={formData.materialDistributor.representativeName}
                  onChange={(e) => updateNested('materialDistributor', 'representativeName', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>전화번호</Label>
                <Input
                  value={formData.materialDistributor.phone}
                  onChange={(e) => updateNested('materialDistributor', 'phone', e.target.value)}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 공사시공자 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">공사시공자 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label>회사명</Label>
                <Input
                  value={formData.constructorInfo.companyName}
                  onChange={(e) => updateNested('constructorInfo', 'companyName', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>회사주소</Label>
                <Input
                  value={formData.constructorInfo.companyAddress}
                  onChange={(e) => updateNested('constructorInfo', 'companyAddress', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>성명</Label>
                <Input
                  value={formData.constructorInfo.name}
                  onChange={(e) => updateNested('constructorInfo', 'name', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>전화번호</Label>
                <Input
                  value={formData.constructorInfo.phone}
                  onChange={(e) => updateNested('constructorInfo', 'phone', e.target.value)}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 공사감리자 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">공사감리자 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label>사무소명</Label>
                <Input
                  value={formData.supervisor.officeName}
                  onChange={(e) => updateNested('supervisor', 'officeName', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>사무소주소</Label>
                <Input
                  value={formData.supervisor.officeAddress}
                  onChange={(e) => updateNested('supervisor', 'officeAddress', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>성명</Label>
                <Input
                  value={formData.supervisor.name}
                  onChange={(e) => updateNested('supervisor', 'name', e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label>전화번호</Label>
                <Input
                  value={formData.supervisor.phone}
                  onChange={(e) => updateNested('supervisor', 'phone', e.target.value)}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 검사 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">검사 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label>검사방문요청일</Label>
                <DatePicker
                  value={formData.scheduleInfo.visitRequestDate}
                  onChange={(date) => updateNested('scheduleInfo', 'visitRequestDate', date)}
                />
              </div>
              <div className="space-y-2">
                <Label>검사시작일</Label>
                <DatePicker
                  value={formData.scheduleInfo.startDate}
                  onChange={(date) => updateNested('scheduleInfo', 'startDate', date)}
                />
              </div>
              <div className="space-y-2">
                <Label>검사종료일</Label>
                <DatePicker
                  value={formData.scheduleInfo.endDate}
                  onChange={(date) => updateNested('scheduleInfo', 'endDate', date)}
                />
              </div>
              <div className="space-y-2">
                <Label>검사자</Label>
                <Input
                  value={formData.scheduleInfo.inspector}
                  onChange={(e) => updateNested('scheduleInfo', 'inspector', e.target.value)}
                />
              </div>
            </div>
            {/* 현장 주소 */}
            <div className="mt-4 grid grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label>우편번호</Label>
                <div className="flex gap-2">
                  <Input
                    value={formData.scheduleInfo.sitePostalCode}
                    onChange={(e) => updateNested('scheduleInfo', 'sitePostalCode', e.target.value)}
                    className="w-28"
                  />
                  <Button variant="outline" size="sm" type="button" onClick={openPostcode}>
                    우편번호 찾기
                  </Button>
                </div>
              </div>
              <div className="space-y-2 col-span-2">
                <Label>주소</Label>
                <Input
                  value={formData.scheduleInfo.siteAddress}
                  onChange={(e) => updateNested('scheduleInfo', 'siteAddress', e.target.value)}
                  readOnly
                />
              </div>
              <div className="space-y-2">
                <Label>상세주소</Label>
                <Input
                  value={formData.scheduleInfo.siteAddressDetail}
                  onChange={(e) => updateNested('scheduleInfo', 'siteAddressDetail', e.target.value)}
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 수주 설정 정보 */}
        <Card>
          <CardHeader className="space-y-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <CardTitle className="text-base">수주 설정 정보</CardTitle>
                <Button variant="outline" size="sm" type="button" onClick={() => setOrderModalOpen(true)}>
                  <Plus className="w-4 h-4 mr-1" />
                  수주 선택
                </Button>
              </div>
              <div className="flex items-center gap-3 text-sm">
                <span>전체: <strong>{orderSummary.total}</strong>건</span>
              </div>
            </div>
            {renderFqcProgressBar}
          </CardHeader>
          <CardContent className="p-4">
            {renderEditOrderAccordion(orderGroups)}
          </CardContent>
        </Card>
      </div>
    );
  }, [inspection, formData, orderSummary, orderGroups, updateField, updateNested, handleRemoveOrderItem, handleOpenInspectionInput, handleUpdateOrderItemField, orderModalOpen, renderFqcBadge, renderFqcProgressBar, openPostcode]);

  // ===== 모드 & Config =====
  const mode = isEditMode ? 'edit' : 'view';

  const dynamicConfig = useMemo(() => {
    const base = isEditMode ? { ...inspectionConfig, title: '제품검사' } : inspectionConfig;
    if (inspection?.status === '완료') {
      return { ...base, permissions: { ...base.permissions, canEdit: false } };
    }
    return base;
  }, [isEditMode, inspection?.status]);

  // 데이터 없음
  if (!isLoading && !inspection) {
    return (
      <ServerErrorPage
        title="제품검사 정보를 불러올 수 없습니다"
        message="제품검사 데이터를 찾을 수 없습니다."
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return (
    <>
      <IntegratedDetailTemplate
        config={dynamicConfig}
        mode={mode}
        initialData={{}}
        itemId={id}
        isLoading={isLoading}
        onSubmit={handleSubmit}
        onEdit={inspection?.status !== '완료' ? handleEdit : undefined}
        headerActions={headerActions}
        renderView={() => renderViewContent()}
        renderForm={() => renderFormContent()}
        isSubmitting={isSubmitting}
      />

      {/* 검사 완료 확인 다이얼로그 */}
      <AlertDialog open={showCompleteDialog} onOpenChange={setShowCompleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>검사 완료 처리</AlertDialogTitle>
            <AlertDialogDescription>
              이 제품검사를 완료 처리하시겠습니까?
              <br />
              완료 처리 후에는 상태를 변경할 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isCompleting}>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleComplete}
              disabled={isCompleting}
              className="bg-green-600 hover:bg-green-700"
            >
              {isCompleting ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  처리 중...
                </>
              ) : (
                '검사 완료'
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 수주 선택 모달 */}
      <OrderSelectModal
        open={orderModalOpen}
        onOpenChange={setOrderModalOpen}
        onSelect={handleOrderSelect}
        excludeIds={excludeOrderIds}
        filterClientId={orderFilter.clientId}
        filterItemId={orderFilter.itemId}
        filterLabel={orderFilter.label}
      />

      {/* 거래처(수주처) 검색 모달 */}
      <SupplierSearchModal
        open={clientModalOpen}
        onOpenChange={setClientModalOpen}
        onSelectSupplier={(supplier) => {
          updateField('clientId', Number(supplier.id));
          updateField('client', supplier.name);
          setClientModalOpen(false);
        }}
      />

      {/* 제품검사요청서 모달 */}
      <InspectionRequestModal
        open={requestDocOpen}
        onOpenChange={setRequestDocOpen}
        data={inspection ? buildRequestDocumentData(inspection) : null}
        requestDocumentId={inspection?.requestDocumentId}
      />

      {/* 제품검사성적서 모달 */}
      <InspectionReportModal
        open={reportDocOpen}
        onOpenChange={setReportDocOpen}
        data={inspection ? buildReportDocumentData(inspection, isEditMode ? formData.orderItems : undefined) : null}
        inspection={inspection}
        orderItems={isEditMode ? formData.orderItems : inspection?.orderItems}
      />

      {/* 제품검사 입력 모달 */}
      <ProductInspectionInputModal
        open={inspectionInputOpen}
        onOpenChange={(open) => { setInspectionInputOpen(open); if (!open) setSelectedOrderItem(null); }}
        orderItemId={selectedOrderItem?.id || ''}
        productName="방화셔터"
        specification={selectedOrderItem ? `${selectedOrderItem.orderWidth}x${selectedOrderItem.orderHeight}` : ''}
        initialData={selectedOrderItem?.inspectionData}
        onComplete={handleInspectionComplete}
        fqcDocumentId={selectedOrderItem?.documentId ?? null}
        constructionWidth={selectedOrderItem?.constructionWidth}
        constructionHeight={selectedOrderItem?.constructionHeight}
        changeReason={selectedOrderItem?.changeReason}
        orderItems={isEditMode ? formData.orderItems : (inspection?.orderItems || [])}
        onNavigate={(item) => setSelectedOrderItem(item)}
        readonly={inspection?.status === '완료'}
      />
    </>
  );
}
