'use client';

/**
 * 제품검사 입력 모달
 *
 * 양식 기반 전환 (5.2.4):
 * - FQC 모드: documents API template 기반으로 검사항목 렌더링
 *   → 11개 설치 후 최종검사 항목 (template_id: 65)
 *   → 모두 visual/checkbox (적합/부적합)
 *   → saveFqcDocument로 서버에 직접 저장
 * - Legacy 모드: 기존 하드코딩 필드 (fallback)
 */

import { useState, useEffect, useRef, useCallback } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2, ChevronLeft, ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { getFqcTemplate, getFqcDocument, saveFqcDocument } from './fqcActions';
import type { FqcTemplate, FqcTemplateItem, FqcDocumentData } from './fqcActions';
import type { ProductInspectionData, OrderSettingItem } from './types';

type JudgmentValue = '적합' | '부적합' | null;

interface ConstructionInfo {
  width: number | null;
  height: number | null;
  changeReason: string;
}

interface ProductInspectionInputModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  orderItemId: string;
  productName?: string;
  specification?: string;
  initialData?: ProductInspectionData;
  onComplete: (data: ProductInspectionData, constructionInfo?: ConstructionInfo) => void;
  /** FQC 문서 ID (있으면 양식 기반 모드) */
  fqcDocumentId?: number | null;
  /** 시공 가로/세로 초기값 */
  constructionWidth?: number | null;
  constructionHeight?: number | null;
  /** 변경사유 초기값 */
  changeReason?: string;
  /** 전체 주문 아이템 목록 (이전/다음 네비게이션용) */
  orderItems?: OrderSettingItem[];
  /** 이전/다음 이동 시 호출 (저장 후 해당 아이템으로 전환) */
  onNavigate?: (item: OrderSettingItem) => void;
  /** 읽기전용 모드 (완료된 검사) */
  readonly?: boolean;
}

export function ProductInspectionInputModal({
  open,
  onOpenChange,
  orderItemId,
  productName = '',
  specification = '',
  initialData,
  onComplete,
  fqcDocumentId,
  constructionWidth: initialConstructionWidth,
  constructionHeight: initialConstructionHeight,
  changeReason: initialChangeReason = '',
  orderItems = [],
  onNavigate,
  readonly = false,
}: ProductInspectionInputModalProps) {
  // FQC 모드 상태
  const [fqcTemplate, setFqcTemplate] = useState<FqcTemplate | null>(null);
  const [, setFqcDocData] = useState<FqcDocumentData[]>([]);
  const [isLoadingFqc, setIsLoadingFqc] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // 시공 가로/세로/변경사유
  const [conWidth, setConWidth] = useState<number | null>(null);
  const [conHeight, setConHeight] = useState<number | null>(null);
  const [changeReason, setChangeReason] = useState('');

  // 판정 상태 (FQC 모드)
  const [judgments, setJudgments] = useState<Record<number, JudgmentValue>>({});

  const useFqcMode = !!fqcDocumentId;

  // FQC 데이터 로드
  useEffect(() => {
    if (!open || !useFqcMode) return;

    setIsLoadingFqc(true);

    Promise.all([
      getFqcTemplate(),
      getFqcDocument(fqcDocumentId!),
    ])
      .then(([templateResult, docResult]) => {
        if (templateResult.success && templateResult.data) {
          setFqcTemplate(templateResult.data);
        }
        if (docResult.success && docResult.data) {
          setFqcDocData(docResult.data.data);
          // 기존 판정 데이터 복원
          const dataSection = docResult.data.template.sections.find(s => s.items.length > 0);
          const judgmentCol = docResult.data.template.columns.find(c => c.label === '판정');
          if (dataSection && judgmentCol) {
            const map: Record<number, JudgmentValue> = {};
            for (const d of docResult.data.data) {
              if (d.sectionId === dataSection.id && d.columnId === judgmentCol.id && d.fieldKey === 'result') {
                map[d.rowIndex] = (d.fieldValue as JudgmentValue) ?? null;
              }
            }
            setJudgments(map);
          }
        }
      })
      .finally(() => setIsLoadingFqc(false));
  }, [open, useFqcMode, fqcDocumentId]);

  // 모달 열릴 때 또는 아이템 전환 시 시공 사이즈/변경사유 초기화
  useEffect(() => {
    if (open) {
      setConWidth(initialConstructionWidth ?? null);
      setConHeight(initialConstructionHeight ?? null);
      setChangeReason(initialChangeReason);
    }
  }, [open, orderItemId, initialConstructionWidth, initialConstructionHeight, initialChangeReason]);

  // 모달 닫힐 때 상태 초기화
  useEffect(() => {
    if (!open) {
      setJudgments({});
      setFqcDocData([]);
    }
  }, [open]);

  // 판정 토글
  const toggleJudgment = useCallback((rowIndex: number, value: JudgmentValue) => {
    setJudgments(prev => ({
      ...prev,
      [rowIndex]: prev[rowIndex] === value ? null : value,
    }));
  }, []);

  // FQC 종합판정 계산
  const overallJudgment = useCallback((): '합격' | '불합격' | null => {
    if (!fqcTemplate) return null;
    const dataSection = fqcTemplate.sections.find(s => s.items.length > 0);
    if (!dataSection || dataSection.items.length === 0) return null;

    const values = dataSection.items.map((_, idx) => judgments[idx]);
    const hasValue = values.some(v => v !== undefined && v !== null);
    if (!hasValue) return null;
    if (values.some(v => v === '부적합')) return '불합격';
    if (values.every(v => v === '적합')) return '합격';
    return null;
  }, [fqcTemplate, judgments]);

  // FQC 검사 완료 (서버 저장)
  const handleFqcComplete = useCallback(async (closeModal = true) => {
    if (!fqcTemplate || !fqcDocumentId) return;

    const dataSection = fqcTemplate.sections.find(s => s.items.length > 0);
    const judgmentCol = fqcTemplate.columns.find(c => c.label === '판정');
    if (!dataSection || !judgmentCol) return;

    setIsSaving(true);
    try {
      const records: Array<{
        section_id: number | null;
        column_id: number | null;
        row_index: number;
        field_key: string;
        field_value: string | null;
      }> = [];

      dataSection.items.forEach((_, idx) => {
        const value = judgments[idx];
        if (value) {
          records.push({
            section_id: dataSection.id,
            column_id: judgmentCol.id,
            row_index: idx,
            field_key: 'result',
            field_value: value,
          });
        }
      });

      records.push({
        section_id: null,
        column_id: null,
        row_index: 0,
        field_key: 'footer_judgement',
        field_value: overallJudgment(),
      });

      const result = await saveFqcDocument({
        documentId: fqcDocumentId,
        data: records,
      });

      if (result.success) {
        toast.success('검사 데이터가 저장되었습니다.');

        const legacyData: ProductInspectionData = {
          productName,
          specification,
          productImages: [],
          appearanceProcessing: judgments[0] === '적합' ? 'pass' : judgments[0] === '부적합' ? 'fail' : null,
          appearanceSewing: judgments[1] === '적합' ? 'pass' : judgments[1] === '부적합' ? 'fail' : null,
          appearanceAssembly: judgments[2] === '적합' ? 'pass' : judgments[2] === '부적합' ? 'fail' : null,
          appearanceSmokeBarrier: judgments[3] === '적합' ? 'pass' : judgments[3] === '부적합' ? 'fail' : null,
          appearanceBottomFinish: judgments[4] === '적합' ? 'pass' : judgments[4] === '부적합' ? 'fail' : null,
          motor: judgments[5] === '적합' ? 'pass' : judgments[5] === '부적합' ? 'fail' : null,
          material: judgments[6] === '적합' ? 'pass' : judgments[6] === '부적합' ? 'fail' : null,
          lengthValue: null,
          lengthJudgment: judgments[7] === '적합' ? 'pass' : judgments[7] === '부적합' ? 'fail' : null,
          heightValue: null,
          heightJudgment: judgments[8] === '적합' ? 'pass' : judgments[8] === '부적합' ? 'fail' : null,
          guideRailGapValue: null,
          guideRailGap: judgments[9] === '적합' ? 'pass' : judgments[9] === '부적합' ? 'fail' : null,
          bottomFinishGapValue: null,
          bottomFinishGap: judgments[10] === '적합' ? 'pass' : judgments[10] === '부적합' ? 'fail' : null,
          fireResistanceTest: null,
          smokeLeakageTest: null,
          openCloseTest: null,
          impactTest: null,
          hasSpecialNotes: false,
          specialNotes: '',
        };

        onComplete(legacyData, { width: conWidth, height: conHeight, changeReason });
        if (closeModal) onOpenChange(false);
      } else {
        toast.error(result.error || '검사 데이터 저장에 실패했습니다.');
      }
    } finally {
      setIsSaving(false);
    }
  }, [fqcTemplate, fqcDocumentId, judgments, overallJudgment, productName, specification, conWidth, conHeight, changeReason, onComplete, onOpenChange]);

  // ===== Legacy 모드 상태 =====
  const [legacyFormData, setLegacyFormData] = useState<ProductInspectionData | null>(null);

  useEffect(() => {
    if (open && !useFqcMode) {
      setLegacyFormData(initialData || {
        productName,
        specification,
        productImages: [],
        appearanceProcessing: null,
        appearanceSewing: null,
        appearanceAssembly: null,
        appearanceSmokeBarrier: null,
        appearanceBottomFinish: null,
        motor: null,
        material: null,
        lengthValue: null,
        lengthJudgment: null,
        heightValue: null,
        heightJudgment: null,
        guideRailGapValue: null,
        guideRailGap: null,
        bottomFinishGapValue: null,
        bottomFinishGap: null,
        fireResistanceTest: null,
        smokeLeakageTest: null,
        openCloseTest: null,
        impactTest: null,
        hasSpecialNotes: false,
        specialNotes: '',
      });
    }
  }, [open, orderItemId, useFqcMode, initialData, productName, specification]);

  // Legacy 완료 핸들러
  const handleLegacyComplete = useCallback(() => {
    if (!legacyFormData) return;
    onComplete(legacyFormData, { width: conWidth, height: conHeight, changeReason });
    onOpenChange(false);
  }, [legacyFormData, conWidth, conHeight, changeReason, onComplete, onOpenChange]);

  // ===== 이전/다음 네비게이션 =====
  const currentIndex = orderItems.findIndex(item => item.id === orderItemId);
  const totalItems = orderItems.length;
  const hasPrev = currentIndex > 0;
  const hasNext = currentIndex < totalItems - 1;

  const hasLegacyChanges = useCallback(() => {
    if (!legacyFormData) return false;
    // 검사 데이터 변경 확인
    if (JSON.stringify(legacyFormData) !== JSON.stringify(initialData ?? null)) return true;
    // 시공 사이즈/변경사유 변경 확인
    if (conWidth !== (initialConstructionWidth ?? null)) return true;
    if (conHeight !== (initialConstructionHeight ?? null)) return true;
    if (changeReason !== initialChangeReason) return true;
    return false;
  }, [legacyFormData, initialData, conWidth, conHeight, changeReason, initialConstructionWidth, initialConstructionHeight, initialChangeReason]);

  const saveAndNavigate = useCallback(async (targetItem: OrderSettingItem) => {
    if (!onNavigate) return;
    // readonly 모드에서는 저장 없이 이동만
    if (!readonly) {
      // 변경된 내용이 있을 때만 저장
      if (useFqcMode) {
        // FQC: judgments 변경 확인
        const hasJudgmentChanges = Object.keys(judgments).length > 0;
        if (hasJudgmentChanges) await handleFqcComplete(false);
      } else if (legacyFormData && hasLegacyChanges()) {
        onComplete(legacyFormData, { width: conWidth, height: conHeight, changeReason });
      }
    }
    // 다음 아이템으로 이동
    onNavigate(targetItem);
  }, [useFqcMode, handleFqcComplete, legacyFormData, judgments, conWidth, conHeight, changeReason, hasLegacyChanges, onComplete, onNavigate]);

  const handlePrev = useCallback(() => {
    if (hasPrev) saveAndNavigate(orderItems[currentIndex - 1]);
  }, [hasPrev, currentIndex, orderItems, saveAndNavigate]);

  const handleNext = useCallback(() => {
    if (hasNext) saveAndNavigate(orderItems[currentIndex + 1]);
  }, [hasNext, currentIndex, orderItems, saveAndNavigate]);

  // FQC 데이터 섹션
  const dataSection = fqcTemplate?.sections.find(s => s.items.length > 0);
  const sortedItems = dataSection?.items.sort((a, b) => a.sortOrder - b.sortOrder) || [];
  const currentOverallJudgment = overallJudgment();

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-[95vw] max-w-[600px] max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="text-lg font-bold">
            # 제품검사
            {useFqcMode && (
              <span className="ml-2 text-xs font-normal text-blue-600 bg-blue-50 px-2 py-0.5 rounded">
                양식 기반
              </span>
            )}
          </DialogTitle>
        </DialogHeader>

        {/* 이전/다음 네비게이션 */}
        {totalItems > 1 && (
          <div className="flex items-center justify-between py-2 px-1 border-b">
            <Button
              variant="outline"
              size="sm"
              onClick={handlePrev}
              disabled={!hasPrev || isSaving}
              className="h-8"
            >
              <ChevronLeft className="w-4 h-4 mr-1" />
              이전
            </Button>
            <div className="flex items-center gap-2 text-sm">
              <span className="font-medium">{currentIndex + 1}</span>
              <span className="text-muted-foreground">/ {totalItems}</span>
              {orderItems[currentIndex] && (
                <span className="text-xs text-muted-foreground ml-1">
                  ({orderItems[currentIndex].floor}-{orderItems[currentIndex].symbol})
                </span>
              )}
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={handleNext}
              disabled={!hasNext || isSaving}
              className="h-8"
            >
              다음
              <ChevronRight className="w-4 h-4 ml-1" />
            </Button>
          </div>
        )}

        <div className="space-y-6 mt-4 overflow-y-auto flex-1 pr-2">
          {/* 제품명 / 규격 */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <span className="text-sm text-muted-foreground">제품명</span>
              <div className="font-medium">{productName || '-'}</div>
            </div>
            <div className="space-y-1">
              <span className="text-sm text-muted-foreground">규격</span>
              <div className="font-medium">{specification || '-'}</div>
            </div>
          </div>

          {/* 시공 가로/세로 + 변경사유 */}
          <div className="grid grid-cols-5 gap-3">
            <div className="space-y-1">
              <span className="text-sm text-muted-foreground">시공 가로</span>
              <input
                type="number"
                value={conWidth ?? ''}
                onChange={(e) => setConWidth(e.target.value ? Number(e.target.value) : null)}
                className={cn("w-full h-9 px-3 rounded-md border border-input bg-background text-sm", readonly && "bg-muted cursor-not-allowed")}
                placeholder="가로"
                disabled={readonly}
              />
            </div>
            <div className="space-y-1">
              <span className="text-sm text-muted-foreground">시공 세로</span>
              <input
                type="number"
                value={conHeight ?? ''}
                onChange={(e) => setConHeight(e.target.value ? Number(e.target.value) : null)}
                className={cn("w-full h-9 px-3 rounded-md border border-input bg-background text-sm", readonly && "bg-muted cursor-not-allowed")}
                placeholder="세로"
                disabled={readonly}
              />
            </div>
            <div className="space-y-1 col-span-3">
              <span className="text-sm text-muted-foreground">변경사유</span>
              <input
                type="text"
                value={changeReason}
                onChange={(e) => setChangeReason(e.target.value)}
                className={cn("w-full h-9 px-3 rounded-md border border-input bg-background text-sm", readonly && "bg-muted cursor-not-allowed")}
                placeholder="변경사유 입력"
                disabled={readonly}
              />
            </div>
          </div>

          {useFqcMode ? (
            // ===== FQC 양식 기반 모드 =====
            isLoadingFqc ? (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
                <span className="ml-2 text-muted-foreground text-sm">양식 로딩 중...</span>
              </div>
            ) : (
              <>
                {/* 검사항목 목록 (template 기반) */}
                <div className="space-y-3">
                  <div className="flex items-center justify-between border-b pb-2">
                    <div className="text-sm font-medium text-blue-600">
                      {dataSection?.title || dataSection?.name || '검사항목'}
                      <span className="ml-2 text-xs text-muted-foreground font-normal">
                        ({sortedItems.length}항목)
                      </span>
                    </div>
                    {!readonly && (() => {
                      const allPassed = sortedItems.length > 0 && sortedItems.every((_, idx) => judgments[idx] === '적합');
                      return allPassed ? (
                        <button
                          type="button"
                          onClick={() => setJudgments({})}
                          className="px-4 py-2 rounded-lg text-sm font-medium bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors"
                        >
                          초기화
                        </button>
                      ) : (
                        <button
                          type="button"
                          onClick={() => {
                            const allPass: Record<number, JudgmentValue> = {};
                            sortedItems.forEach((_, idx) => { allPass[idx] = '적합'; });
                            setJudgments(allPass);
                          }}
                          className="px-4 py-2 rounded-lg text-sm font-medium bg-orange-500 text-white hover:bg-orange-600 transition-colors"
                        >
                          일괄합격
                        </button>
                      );
                    })()}
                  </div>

                  <div className="space-y-2">
                    {sortedItems.map((item, idx) => (
                      <FqcInspectionRow
                        key={item.id}
                        index={idx}
                        item={item}
                        judgment={judgments[idx] ?? null}
                        onToggle={toggleJudgment}
                        readonly={readonly}
                      />
                    ))}
                  </div>
                </div>

                {/* 종합판정 */}
                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border">
                  <span className="font-medium">종합판정</span>
                  <span
                    className={cn(
                      'font-bold text-sm',
                      currentOverallJudgment === '합격'
                        ? 'text-blue-600'
                        : currentOverallJudgment === '불합격'
                          ? 'text-red-600'
                          : 'text-gray-400'
                    )}
                  >
                    {currentOverallJudgment || '미판정'}
                  </span>
                </div>
              </>
            )
          ) : (
            // ===== Legacy 하드코딩 모드 (fallback) =====
            legacyFormData && (
              <LegacyInspectionForm
                data={legacyFormData}
                onChange={setLegacyFormData}
                readonly={readonly}
              />
            )
          )}
        </div>

        {/* 버튼 영역 */}
        <div className="flex gap-3 mt-6 pt-4 border-t">
          <Button variant="outline" onClick={() => onOpenChange(false)} className="flex-1">
            {readonly ? '닫기' : '취소'}
          </Button>
          {!readonly && (
            <Button
              onClick={useFqcMode ? () => handleFqcComplete(true) : handleLegacyComplete}
              disabled={isSaving || isLoadingFqc}
              className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
            >
              {isSaving ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  저장 중...
                </>
              ) : (
                '검사 완료'
              )}
            </Button>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ===== FQC 검사항목 행 =====

function FqcInspectionRow({
  index,
  item,
  judgment,
  onToggle,
  readonly = false,
}: {
  index: number;
  item: FqcTemplateItem;
  judgment: JudgmentValue;
  onToggle: (rowIndex: number, value: JudgmentValue) => void;
  readonly?: boolean;
}) {
  return (
    <div className="flex items-center justify-between py-2 px-3 rounded-lg hover:bg-gray-50">
      <div className="flex items-center gap-3">
        <span className="text-xs text-muted-foreground w-5 text-right">{index + 1}</span>
        <span className="text-sm">{item.itemName}</span>
      </div>
      <div className="flex gap-2">
        <button
          type="button"
          onClick={() => !readonly && onToggle(index, '적합')}
          disabled={readonly}
          className={cn(
            'px-3 py-1.5 rounded text-xs font-medium transition-colors',
            judgment === '적합'
              ? 'bg-blue-600 text-white'
              : 'bg-gray-100 text-gray-600',
            readonly
              ? 'cursor-not-allowed opacity-70'
              : judgment !== '적합' && 'hover:bg-blue-50 hover:text-blue-600'
          )}
        >
          적합
        </button>
        <button
          type="button"
          onClick={() => !readonly && onToggle(index, '부적합')}
          disabled={readonly}
          className={cn(
            'px-3 py-1.5 rounded text-xs font-medium transition-colors',
            judgment === '부적합'
              ? 'bg-red-600 text-white'
              : 'bg-gray-100 text-gray-600',
            readonly
              ? 'cursor-not-allowed opacity-70'
              : judgment !== '부적합' && 'hover:bg-red-50 hover:text-red-600'
          )}
        >
          부적합
        </button>
      </div>
    </div>
  );
}

// ===== Legacy 폼 (기존 하드코딩 검사항목) =====

function LegacyInspectionForm({
  data,
  onChange,
  readonly = false,
}: {
  data: ProductInspectionData;
  onChange: (data: ProductInspectionData) => void;
  readonly?: boolean;
}) {
  const update = <K extends keyof ProductInspectionData>(key: K, value: ProductInspectionData[K]) => {
    onChange({ ...data, [key]: value });
  };

  const judgmentKeys: (keyof ProductInspectionData)[] = [
    'appearanceProcessing', 'appearanceSewing', 'appearanceAssembly',
    'appearanceSmokeBarrier', 'appearanceBottomFinish', 'motor', 'material',
    'lengthJudgment', 'heightJudgment', 'guideRailGap', 'bottomFinishGap',
    'fireResistanceTest', 'smokeLeakageTest', 'openCloseTest', 'impactTest',
  ];

  const allPassed = judgmentKeys.every(k => data[k] === 'pass');

  const setAllPass = () => {
    const updated = { ...data };
    judgmentKeys.forEach(k => { (updated as Record<string, unknown>)[k] = 'pass'; });
    onChange(updated);
  };

  const resetAll = () => {
    const updated = { ...data };
    judgmentKeys.forEach(k => { (updated as Record<string, unknown>)[k] = null; });
    onChange(updated);
  };

  return (
    <>
      {!readonly && (
        <div className="flex justify-end">
          {allPassed ? (
            <button
              type="button"
              onClick={resetAll}
              className="px-4 py-2 rounded-lg text-sm font-medium bg-gray-200 text-gray-700 hover:bg-gray-300 transition-colors"
            >
              초기화
            </button>
          ) : (
            <button
              type="button"
              onClick={setAllPass}
              className="px-4 py-2 rounded-lg text-sm font-medium bg-orange-500 text-white hover:bg-orange-600 transition-colors"
            >
              일괄합격
            </button>
          )}
        </div>
      )}
      {/* 1. 겉모양 검사 */}
      <LegacyGroup title="1. 겉모양">
        <LegacyRow label="가공상태" criteria="사용상 해로운 결함이 없을 것" value={data.appearanceProcessing} onChange={v => update('appearanceProcessing', v)} readonly={readonly} />
        <LegacyRow label="재봉상태" criteria="내화실에 의해 견고하게 접합되어야 함" value={data.appearanceSewing} onChange={v => update('appearanceSewing', v)} readonly={readonly} />
        <LegacyRow label="조립상태" criteria="핸드링이 견고하게 조립되어야 함" value={data.appearanceAssembly} onChange={v => update('appearanceAssembly', v)} readonly={readonly} />
        <LegacyRow label="연기차단재" criteria="케이스 W80, 가이드레일 W50(양쪽 설치)" value={data.appearanceSmokeBarrier} onChange={v => update('appearanceSmokeBarrier', v)} readonly={readonly} />
        <LegacyRow label="하단마감재" criteria="내부 무겁방절 설치 유무" value={data.appearanceBottomFinish} onChange={v => update('appearanceBottomFinish', v)} readonly={readonly} />
      </LegacyGroup>
      {/* 2. 모터 */}
      <LegacyGroup title="2. 모터">
        <LegacyRow label="모터" criteria="인정제품과 동일사양" value={data.motor} onChange={v => update('motor', v)} readonly={readonly} />
      </LegacyGroup>
      {/* 3. 재질 */}
      <LegacyGroup title="3. 재질">
        <LegacyRow label="재질" criteria="WY-SC780 인쇄상태 확인" value={data.material} onChange={v => update('material', v)} readonly={readonly} />
      </LegacyGroup>
      {/* 4. 치수(오픈사이즈) */}
      <LegacyGroup title="4. 치수(오픈사이즈)">
        <LegacyRow label="길이" criteria="수주 치수 ± 30mm" value={data.lengthJudgment} onChange={v => update('lengthJudgment', v)} readonly={readonly} />
        <LegacyRow label="높이" criteria="수주 치수 ± 30mm" value={data.heightJudgment} onChange={v => update('heightJudgment', v)} readonly={readonly} />
        <LegacyRow label="가이드레일 간격" criteria="10 ± 5mm (측정부위 높이 100 이하)" value={data.guideRailGap} onChange={v => update('guideRailGap', v)} readonly={readonly} />
        <LegacyRow label="하단막대 간격" criteria="가이드레일과 하단마감재 측 사이 25mm 이내" value={data.bottomFinishGap} onChange={v => update('bottomFinishGap', v)} readonly={readonly} />
      </LegacyGroup>
      {/* 5~9. 시험 검사 */}
      <LegacyGroup title="5~9. 시험 검사">
        <LegacyRow label="내화시험" criteria="비차열/차열성 - 공인시험기관 시험성적서" value={data.fireResistanceTest} onChange={v => update('fireResistanceTest', v)} readonly={readonly} />
        <LegacyRow label="차연시험" criteria="25Pa 시 공기누설량 0.9m³/min·m² 이하" value={data.smokeLeakageTest} onChange={v => update('smokeLeakageTest', v)} readonly={readonly} />
        <LegacyRow label="개폐시험" criteria="전동개폐 2.5~6.5m/min, 자중강하 3~7m/min" value={data.openCloseTest} onChange={v => update('openCloseTest', v)} readonly={readonly} />
        <LegacyRow label="내충격시험" criteria="방화상 유해한 파괴, 박리 탈락 유무" value={data.impactTest} onChange={v => update('impactTest', v)} readonly={readonly} />
      </LegacyGroup>
      {/* 사진 첨부 */}
      <LegacyGroup title="제품 사진">
        <LegacyPhotoUpload
          images={data.productImages}
          onChange={(images) => update('productImages', images)}
          maxCount={2}
          readonly={readonly}
        />
      </LegacyGroup>
      {/* 특이사항 */}
      <LegacyGroup title="특이사항">
        <textarea
          value={data.specialNotes ?? ''}
          onChange={(e) => update('specialNotes', e.target.value)}
          className={cn("w-full min-h-[60px] px-3 py-2 rounded-md border border-input bg-background text-sm resize-none", readonly && "bg-muted cursor-not-allowed")}
          placeholder="특이사항 입력"
          disabled={readonly}
        />
      </LegacyGroup>
    </>
  );
}

function LegacyGroup({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="space-y-3">
      <div className="text-sm font-medium text-orange-500 border-b pb-2">{title}</div>
      <div className="space-y-4 pl-2">{children}</div>
    </div>
  );
}

function LegacyRow({
  label,
  criteria,
  value,
  onChange,
  readonly = false,
}: {
  label: string;
  criteria?: string;
  value: 'pass' | 'fail' | null;
  onChange: (v: 'pass' | 'fail') => void;
  readonly?: boolean;
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <div className="flex-1 min-w-0">
        <span className="text-sm font-medium">{label}</span>
        {criteria && <p className="text-xs text-muted-foreground mt-0.5">{criteria}</p>}
      </div>
      <div className="flex gap-2 shrink-0">
        <button
          type="button"
          onClick={() => !readonly && onChange('pass')}
          disabled={readonly}
          className={cn(
            'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
            value === 'pass' ? 'bg-orange-500 text-white' : 'bg-gray-200 text-gray-700',
            readonly
              ? 'cursor-not-allowed opacity-70'
              : value !== 'pass' && 'hover:bg-gray-300'
          )}
        >
          적합
        </button>
        <button
          type="button"
          onClick={() => !readonly && onChange('fail')}
          disabled={readonly}
          className={cn(
            'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
            value === 'fail' ? 'bg-gray-700 text-white' : 'bg-gray-200 text-gray-700',
            readonly
              ? 'cursor-not-allowed opacity-70'
              : value !== 'fail' && 'hover:bg-gray-300'
          )}
        >
          부적합
        </button>
      </div>
    </div>
  );
}

function LegacyPhotoUpload({
  images = [],
  onChange,
  maxCount,
  readonly = false,
}: {
  images: string[];
  onChange: (images: string[]) => void;
  maxCount: number;
  readonly?: boolean;
}) {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;

    Array.from(files).forEach((file) => {
      if (images.length >= maxCount) return;
      const reader = new FileReader();
      reader.onload = (ev) => {
        const dataUrl = ev.target?.result as string;
        onChange([...images, dataUrl].slice(0, maxCount));
      };
      reader.readAsDataURL(file);
    });
    e.target.value = '';
  };

  const removeImage = (index: number) => {
    onChange(images.filter((_, i) => i !== index));
  };

  return (
    <div className="flex gap-3">
      {images.map((src, idx) => (
        <div key={idx} className="relative w-24 h-24 rounded-lg border overflow-hidden group">
          <img src={src} alt={`사진 ${idx + 1}`} className="w-full h-full object-cover" />
          {!readonly && (
            <button
              type="button"
              onClick={() => removeImage(idx)}
              className="absolute top-1 right-1 w-5 h-5 rounded-full bg-black/60 text-white text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
            >
              ✕
            </button>
          )}
        </div>
      ))}
      {!readonly && images.length < maxCount && (
        <button
          type="button"
          onClick={() => fileInputRef.current?.click()}
          className="w-24 h-24 rounded-lg border-2 border-dashed border-gray-300 flex flex-col items-center justify-center text-gray-400 hover:border-blue-400 hover:text-blue-400 transition-colors"
        >
          <span className="text-2xl leading-none">+</span>
          <span className="text-xs mt-1">{images.length}/{maxCount}</span>
        </button>
      )}
      {!readonly && (
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={handleFileChange}
        />
      )}
    </div>
  );
}
