'use client';

/**
 * 모델 등록/수정 폼 — 가이드레일 / 케이스 / 하단마감재 공용
 *
 * 2열 레이아웃 (좌: 기본정보 + PartListEditor, 우: 이미지 + 저장)
 * 타입별 헤더 필드 분기
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { X, Save, Trash2, Loader2, FileText, Pencil, History } from 'lucide-react';
import { DrawingCanvas } from '@/components/items/DrawingCanvas';
import { DocumentViewer } from '@/components/document-system/viewer/DocumentViewer';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Card, CardContent } from '@/components/ui/card';
import { DatePicker } from '@/components/ui/date-picker';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import { toast } from 'sonner';
import { useMenuStore } from '@/stores/menuStore';
import { PartListEditor } from './PartListEditor';
import { BendingSearchModal } from './BendingSearchModal';
import {
  getGuiderailModel,
  createGuiderailModel,
  updateGuiderailModel,
  deleteGuiderailModel,
} from './actions';
import type {
  ModelCategory,
  GuiderailModelDetail,
  ComponentData,
  BendingItem,
} from './types';
import { recalculateSums, getWidthSum, parseApiComponent } from './types';

// --- 카테고리별 설정 ---

interface CategoryFormConfig {
  title: string;
  basePath: string;
  hasItemSep: boolean;
  hasCheckType: boolean;
  checkTypeOptions: string[];
  hasModelSelect: boolean;
  hasFinishingType: boolean;
  hasModelUA: boolean;
  hasFrontBottom: boolean;
  hasRailWidthField: boolean;
  widthLabel: string;
  heightLabel: string;
}

const FORM_CONFIG: Record<ModelCategory, CategoryFormConfig> = {
  GUIDERAIL_MODEL: {
    title: '가이드레일',
    basePath: '/production/bending/guiderail',
    hasItemSep: true,
    hasCheckType: true,
    checkTypeOptions: ['벽면형', '측면형'],
    hasModelSelect: true,
    hasFinishingType: true,
    hasModelUA: true,
    hasFrontBottom: false,
    hasRailWidthField: false,
    widthLabel: '가로(너비)',
    heightLabel: '세로(폭)',
  },
  SHUTTERBOX_MODEL: {
    title: '케이스',
    basePath: '/production/bending/shutterbox',
    hasItemSep: false,
    hasCheckType: true,
    checkTypeOptions: ['양면 점검구', '밑면 점검구', '후면 점검구'],
    hasModelSelect: false,
    hasFinishingType: false,
    hasModelUA: false,
    hasFrontBottom: true,
    hasRailWidthField: true,
    widthLabel: '가로(폭)',
    heightLabel: '세로(높이)',
  },
  BOTTOMBAR_MODEL: {
    title: '하단마감재',
    basePath: '/production/bending/bottombar',
    hasItemSep: true,
    hasCheckType: false,
    checkTypeOptions: [],
    hasModelSelect: true,
    hasFinishingType: true,
    hasModelUA: true,
    hasFrontBottom: false,
    hasRailWidthField: false,
    widthLabel: '가로(폭)',
    heightLabel: '세로(높이)',
  },
};

// --- 컴포넌트 ---

interface BendingModelFormProps {
  id?: string;
  mode: 'new' | 'edit' | 'view';
  category: ModelCategory;
}

interface FormState {
  registration_date: string;
  author: string;
  search_keyword: string;
  memo: string;
  rail_width: string;
  rail_length: string;
  box_width: string;
  box_height: string;
  bar_width: string;
  bar_height: string;
  item_sep: string;
  model_UA: string;
  check_type: string;
  model_name: string;
  finishing_type: string;
  front_bottom_width: string;
}

const INITIAL_STATE: FormState = {
  registration_date: new Date().toISOString().split('T')[0],
  author: '',
  search_keyword: '',
  memo: '',
  rail_width: '',
  rail_length: '',
  box_width: '',
  box_height: '',
  bar_width: '',
  bar_height: '',
  item_sep: '스크린',
  model_UA: '인정',
  check_type: '',
  model_name: '',
  finishing_type: '',
  front_bottom_width: '',
};

export function BendingModelForm({ id, mode, category }: BendingModelFormProps) {
  const router = useRouter();
  const cfg = FORM_CONFIG[category];
  const isNew = mode === 'new';
  const isView = mode === 'view';
  const isEdit = mode === 'edit';
  const disabled = isView;
  const sidebarCollapsed = useMenuStore((state) => state.sidebarCollapsed);

  const [form, setForm] = useState<FormState>(INITIAL_STATE);
  const [components, setComponents] = useState<ComponentData[]>([]);
  const [isLoading, setIsLoading] = useState(!isNew);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [isHistoryOpen, setIsHistoryOpen] = useState(false);
  const [isWorkOrderOpen, setIsWorkOrderOpen] = useState(false);
  const [originalModel, setOriginalModel] = useState<GuiderailModelDetail | null>(null);
  const [isDrawingOpen, setIsDrawingOpen] = useState(false);
  const [drawingImage, setDrawingImage] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setDrawingImage(ev.target?.result as string);
    reader.readAsDataURL(file);
    e.target.value = '';
  }, []);

  // 로그인 사용자 이름 로드
  const [authorName, setAuthorName] = useState('');
  useEffect(() => {
    try {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        const user = JSON.parse(userStr);
        if (user?.name) setAuthorName(user.name);
      }
    } catch { /* ignore */ }
  }, []);

  // 데이터 로드
  useEffect(() => {
    if (!isNew && id) {
      getGuiderailModel(id).then((r) => {
        if (r.success && r.data) {
          const model = r.data as GuiderailModelDetail;
          setOriginalModel(model);
          // 결합형태 이미지 로드
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const modelAny = model as any;
          if (modelAny.image_url) setDrawingImage(modelAny.image_url);
          setForm({
            registration_date: model.registration_date || '',
            author: model.author || '',
            search_keyword: model.search_keyword || '',
            memo: model.memo || '',
            rail_width: model.rail_width ? String(model.rail_width) : '',
            rail_length: model.rail_length ? String(model.rail_length) : '',
            box_width: model.box_width ? String(model.box_width) : '',
            box_height: model.box_height ? String(model.box_height) : '',
            bar_width: (model as any).bar_width ? String((model as any).bar_width) : '',
            bar_height: (model as any).bar_height ? String((model as any).bar_height) : '',
            item_sep: model.item_sep || '스크린',
            model_UA: model.model_UA || '인정',
            check_type: model.check_type || model.exit_direction || '',
            model_name: model.model_name || '',
            finishing_type: model.finishing_type || '',
            front_bottom_width: model.front_bottom_width ? String(model.front_bottom_width) : '',
          });
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          setComponents(
            (model.components || []).map((c: any, i: number) => {
              if (c.inputList) return parseApiComponent(c, i);
              return {
                ...c,
                orderNumber: c.orderNumber || i + 1,
                quantity: c.quantity || 1,
                bendingData: c.bendingData ? recalculateSums(c.bendingData) : [],
                width_sum: c.width_sum || getWidthSum(c.bendingData || []),
                sourceItemId: c.sourceItemId || c.sam_item_id || undefined,
              };
            })
          );
        } else {
          toast.error('데이터를 불러오는데 실패했습니다.');
          router.back();
        }
        setIsLoading(false);
      });
    }
  }, [id, isNew, router]);

  const handleChange = useCallback((field: keyof FormState, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  }, []);

  // 부품 추가 (검색 모달에서)
  const handleAddParts = useCallback((items: BendingItem[]) => {
    const newComponents: ComponentData[] = items.map((item, i) => ({
      orderNumber: components.length + i + 1,
      itemName: item.item_name || item.name,
      material: item.material || '',
      quantity: 1,
      width_sum: item.width_sum || 0,
      bendingData: item.bendingData ? recalculateSums(item.bendingData) : [],
      sourceItemId: item.id,
    }));
    setComponents((prev) => [...prev, ...newComponents]);
    setIsSearchOpen(false);
  }, [components.length]);

  // 저장
  const handleSubmit = useCallback(async () => {
    setIsSaving(true);
    try {
      const payload = {
        item_category: category,
        ...form,
        rail_width: form.rail_width ? Number(form.rail_width) : null,
        rail_length: form.rail_length ? Number(form.rail_length) : null,
        box_width: form.box_width ? Number(form.box_width) : null,
        box_height: form.box_height ? Number(form.box_height) : null,
        bar_width: form.bar_width ? Number(form.bar_width) : null,
        bar_height: form.bar_height ? Number(form.bar_height) : null,
        front_bottom_width: form.front_bottom_width ? Number(form.front_bottom_width) : null,
        components: components.map((c) => ({
          orderNumber: c.orderNumber,
          itemName: c.itemName,
          material: c.material,
          quantity: c.quantity,
          width_sum: c.width_sum,
          bendingData: c.bendingData,
          sourceItemId: c.sourceItemId,
        })),
      };

      const result = isNew
        ? await createGuiderailModel(payload)
        : await updateGuiderailModel(id!, payload);

      if (result.success) {
        toast.success(isNew ? '등록되었습니다.' : '저장되었습니다.');
        router.push(cfg.basePath);
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } finally {
      setIsSaving(false);
    }
  }, [form, components, isNew, id, category, cfg.basePath, router]);

  // 삭제
  const handleDelete = useCallback(async () => {
    if (!id) return;
    setIsDeleting(true);
    try {
      const result = await deleteGuiderailModel(id);
      if (result.success) {
        toast.success('삭제되었습니다.');
        router.push(cfg.basePath);
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
    } finally {
      setIsDeleting(false);
      setIsDeleteOpen(false);
    }
  }, [id, cfg.basePath, router]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-[400px]">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-4 pb-24">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">
          {cfg.title} {isNew ? '등록' : '수정'}
          {!isNew && form.model_name && (
            <span className="ml-2 text-muted-foreground font-normal text-base">{form.model_name}</span>
          )}
        </h1>
        <Button variant="link" className="text-muted-foreground" onClick={() => router.push(cfg.basePath)}>
          ← 목록으로
        </Button>
      </div>

      {/* 2열 레이아웃 */}
      <div className="flex gap-4">
        {/* 좌측 */}
        <div className="flex-1 space-y-4">
          {/* 기본 정보 */}
          <Card>
            <CardContent className="pt-6">
              <h3 className="text-sm font-semibold mb-4">기본 정보</h3>

              {/* 1행: 등록일, 작성자, 검색어, 비고 */}
              <div className="grid grid-cols-4 gap-3 mb-3">
                <div className="space-y-1">
                  <Label className="text-xs">등록일</Label>
                  <DatePicker value={form.registration_date} onChange={(v) => handleChange('registration_date', v)} disabled={disabled} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">작성자</Label>
                  <Input value={authorName || form.author} disabled className="bg-muted" placeholder="자동" />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">검색어</Label>
                  <Input value={form.search_keyword} onChange={(e) => handleChange('search_keyword', e.target.value)} disabled={disabled} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs">비고</Label>
                  <Input value={form.memo} onChange={(e) => handleChange('memo', e.target.value)} disabled={disabled} />
                </div>
              </div>

              {/* 2행: 외형 치수 + 케이스 전용 */}
              <div className="grid grid-cols-4 gap-3 mb-3">
                <div className="space-y-1">
                  <Label className="text-xs text-green-600 font-semibold">{cfg.widthLabel}</Label>
                  <Input type="number" value={category === 'SHUTTERBOX_MODEL' ? form.box_width : category === 'BOTTOMBAR_MODEL' ? form.bar_width : form.rail_width} onChange={(e) => handleChange(category === 'SHUTTERBOX_MODEL' ? 'box_width' : category === 'BOTTOMBAR_MODEL' ? 'bar_width' : 'rail_width', e.target.value)} disabled={disabled} />
                </div>
                <div className="space-y-1">
                  <Label className="text-xs text-red-600 font-semibold">{cfg.heightLabel} {cfg.hasCheckType && category !== 'GUIDERAIL_MODEL' ? '*' : ''}</Label>
                  <Input type="number" value={category === 'SHUTTERBOX_MODEL' ? form.box_height : category === 'BOTTOMBAR_MODEL' ? form.bar_height : form.rail_length} onChange={(e) => handleChange(category === 'SHUTTERBOX_MODEL' ? 'box_height' : category === 'BOTTOMBAR_MODEL' ? 'bar_height' : 'rail_length', e.target.value)} disabled={disabled} />
                </div>
                {cfg.hasModelSelect && (
                  <div className="space-y-1">
                    <Label className="text-xs">모델 <span className="text-red-500">*</span></Label>
                    <Input value={form.model_name} onChange={(e) => handleChange('model_name', e.target.value)} disabled={disabled} />
                  </div>
                )}
                {cfg.hasFinishingType && (
                  <div className="space-y-1">
                    <Label className="text-xs">마감</Label>
                    <Select key={`finish-${form.finishing_type}`} value={form.finishing_type} onValueChange={(v) => handleChange('finishing_type', v)} disabled={disabled}>
                      <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="SUS마감">SUS마감</SelectItem>
                        <SelectItem value="EGI마감">EGI마감</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                )}
                {cfg.hasFrontBottom && (
                  <>
                    <div className="space-y-1">
                      <Label className="text-xs">전면밑</Label>
                      <Input type="number" value={form.front_bottom_width} onChange={(e) => handleChange('front_bottom_width', e.target.value)} disabled={disabled} />
                    </div>
                    {cfg.hasRailWidthField && (
                      <div className="space-y-1">
                        <Label className="text-xs">레일폭</Label>
                        <Input type="number" value={form.rail_width} onChange={(e) => handleChange('rail_width', e.target.value)} disabled={disabled} />
                      </div>
                    )}
                  </>
                )}
              </div>

              {/* 3행: 라디오 그룹 */}
              <div className="flex flex-wrap gap-6 mt-2">
                {cfg.hasItemSep && (
                  <div className="space-y-1">
                    <Label className="text-xs">대분류 <span className="text-red-500">*</span></Label>
                    <RadioGroup value={form.item_sep} onValueChange={(v) => handleChange('item_sep', v)} className="flex gap-4" disabled={disabled}>
                      <div className="flex items-center gap-1"><RadioGroupItem value="스크린" id="sep-screen" /><Label htmlFor="sep-screen" className="text-sm">스크린</Label></div>
                      <div className="flex items-center gap-1"><RadioGroupItem value="철재" id="sep-steel" /><Label htmlFor="sep-steel" className="text-sm">철재</Label></div>
                    </RadioGroup>
                  </div>
                )}

                {cfg.hasCheckType && (
                  <div className="space-y-1">
                    <Label className="text-xs">{category === 'GUIDERAIL_MODEL' ? '형태' : '점검구'} {category !== 'GUIDERAIL_MODEL' ? '*' : ''}</Label>
                    <RadioGroup value={form.check_type} onValueChange={(v) => handleChange('check_type', v)} className="flex gap-4" disabled={disabled}>
                      {cfg.checkTypeOptions.map((opt) => (
                        <div key={opt} className="flex items-center gap-1">
                          <RadioGroupItem value={opt} id={`ct-${opt}`} />
                          <Label htmlFor={`ct-${opt}`} className="text-sm">{opt}</Label>
                        </div>
                      ))}
                    </RadioGroup>
                  </div>
                )}

                {cfg.hasModelUA && (
                  <div className="space-y-1">
                    <Label className="text-xs">모델유형</Label>
                    <RadioGroup value={form.model_UA} onValueChange={(v) => handleChange('model_UA', v)} className="flex gap-4" disabled={disabled}>
                      <div className="flex items-center gap-1"><RadioGroupItem value="인정" id="ua-yes" /><Label htmlFor="ua-yes" className="text-sm">인정</Label></div>
                      <div className="flex items-center gap-1"><RadioGroupItem value="비인정" id="ua-no" /><Label htmlFor="ua-no" className="text-sm">비인정</Label></div>
                    </RadioGroup>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* 부품 조립 */}
          <Card>
            <CardContent className="pt-6">
              <PartListEditor
                components={components}
                onChange={setComponents}
                readOnly={disabled}
                onAddParts={() => setIsSearchOpen(true)}
              />
            </CardContent>
          </Card>
        </div>

        {/* 우측: 이미지 + 저장 */}
        <div className="w-[280px] space-y-4">
          <Card>
            <CardContent className="pt-6">
              <h3 className="text-sm font-semibold mb-3">결합형태 이미지</h3>
              <div className="w-full aspect-square bg-muted/30 border-2 border-dashed rounded-lg flex items-center justify-center mb-3 overflow-hidden">
                {drawingImage ? (
                  <img src={drawingImage} alt="결합형태 이미지" className="w-full h-full object-contain" />
                ) : (
                  <span className="text-sm text-muted-foreground">이미지 없음</span>
                )}
              </div>
              {!disabled && (
                <div className="space-y-2">
                  <div className="flex gap-2">
                    <Button variant="outline" size="sm" className="flex-1 text-xs" onClick={() => fileInputRef.current?.click()}>
                      파일 선택
                    </Button>
                    <Button variant="outline" size="sm" className="text-xs" onClick={() => setIsDrawingOpen(true)}>
                      <Pencil className="h-3 w-3 mr-1" />그리기
                    </Button>
                  </div>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={handleFileChange}
                  />
                  <p className="text-xs text-muted-foreground">Ctrl+V로 붙여넣기 가능</p>
                </div>
              )}
            </CardContent>
          </Card>

        </div>
      </div>

      {/* 하단 Sticky 액션 바 */}
      <div className={`fixed bottom-4 left-4 right-4 px-4 py-3 bg-background/95 backdrop-blur rounded-xl border shadow-lg z-50 transition-all duration-300 md:bottom-6 md:px-6 md:right-[24px] ${sidebarCollapsed ? 'md:left-[120px]' : 'md:left-[280px]'}`}>
        <div className="flex items-center justify-between">
          <Button variant="outline" onClick={() => router.push(cfg.basePath)} size="sm" className="md:size-default">
            <X className="w-4 h-4 md:mr-2" />
            <span className="hidden md:inline">취소</span>
          </Button>
          <div className="flex items-center gap-1 md:gap-2">
            {isEdit && (
              <>
                <Button variant="outline" size="sm" className="md:size-default" onClick={() => setIsHistoryOpen(true)}>
                  <History className="w-4 h-4 md:mr-2" />
                  <span className="hidden md:inline">이력</span>
                </Button>
                <Button variant="outline" size="sm" className="md:size-default" onClick={() => setIsWorkOrderOpen(true)}>
                  <FileText className="w-4 h-4 md:mr-2" />
                  <span className="hidden md:inline">작업지시서</span>
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  className="text-destructive hover:bg-destructive hover:text-destructive-foreground md:size-default"
                  onClick={() => setIsDeleteOpen(true)}
                >
                  <Trash2 className="w-4 h-4 md:mr-2" />
                  <span className="hidden md:inline">삭제</span>
                </Button>
              </>
            )}
            {!disabled && (
              <Button onClick={handleSubmit} disabled={isSaving} size="sm" className="md:size-default">
                {isSaving ? <Loader2 className="w-4 h-4 md:mr-2 animate-spin" /> : <Save className="w-4 h-4 md:mr-2" />}
                <span className="hidden md:inline">저장</span>
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 부품 검색 모달 */}
      <BendingSearchModal
        open={isSearchOpen}
        onOpenChange={setIsSearchOpen}
        onSelect={handleAddParts}
      />

      {/* 수정 이력 */}
      <Dialog open={isHistoryOpen} onOpenChange={setIsHistoryOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>수정 이력</DialogTitle>
          </DialogHeader>
          <div className="space-y-3 text-sm">
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">모델명</span>
              <span className="font-medium">{originalModel?.model_name || form.model_name || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">등록일</span>
              <span>{originalModel?.registration_date || form.registration_date || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">작성자</span>
              <span>{originalModel?.author || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">최종수정자</span>
              <span>{originalModel?.modified_by || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">현재 수정자</span>
              <span className="text-blue-600 font-medium">{authorName || '-'}</span>
            </div>
            <div className="flex justify-between border-b pb-2">
              <span className="text-muted-foreground">생성일시</span>
              <span>{originalModel?.created_at || '-'}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">수정일시</span>
              <span>{originalModel?.updated_at || '-'}</span>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* 작업지시서 — DocumentViewer 쉘 (축소/확대/맞춤/PDF/인쇄) */}
      <DocumentViewer
        title={`절곡 작업일지 — ${form.model_name || cfg.title}`}
        features={{ zoom: true, print: true }}
        actions={['pdf', 'print']}
        open={isWorkOrderOpen}
        onOpenChange={setIsWorkOrderOpen}
      >
        <div className="p-6 space-y-4 bg-white min-h-[600px]">
          {/* 헤더 정보 */}
          <h2 className="text-lg font-bold text-center">{cfg.title} 작업지시서</h2>
          <div className="flex items-center justify-center gap-6 text-sm">
            <div>
              <span className="text-muted-foreground">규격: </span>
              <span className="font-bold text-red-600">
                {category === 'SHUTTERBOX_MODEL'
                  ? `${form.box_width || '-'}*${form.box_height || '-'}`
                  : category === 'BOTTOMBAR_MODEL'
                  ? `${form.bar_width || '-'}×${form.bar_height || '-'}`
                  : `${form.rail_width || '-'}×${form.rail_length || '-'}`}
              </span>
            </div>
            {cfg.hasCheckType && (
              <div>
                <span className="text-muted-foreground">점검구: </span>
                <span className="font-bold">{form.check_type || '-'}</span>
              </div>
            )}
            {cfg.hasFinishingType && (
              <div>
                <span className="text-muted-foreground">마감: </span>
                <span className="font-medium">{form.finishing_type || '-'}</span>
              </div>
            )}
          </div>

          {/* 부품별 절곡 데이터 */}
          {components.map((comp) => (
            <div key={comp.orderNumber} className="border rounded p-3 space-y-2">
              <div className="flex items-center gap-3 text-sm font-medium">
                <span className="px-2 py-0.5 bg-blue-100 text-blue-800 rounded text-xs">순서:{comp.orderNumber}</span>
                <span>{comp.itemName}</span>
                <span className="text-muted-foreground">재질: {comp.material}</span>
                <span className="text-muted-foreground">수량: {comp.quantity}</span>
                <span className="text-blue-600 font-semibold">폭합: {(comp.width_sum || 0).toLocaleString()}</span>
              </div>
              {/* 절곡 치수 테이블 */}
              <table className="w-full text-xs border-collapse">
                <thead>
                  <tr className="bg-muted/50">
                    <th className="border px-2 py-1 w-[60px]">번호</th>
                    {comp.bendingData.map((d) => (
                      <th key={d.no} className="border px-2 py-1 text-center">{d.no}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td className="border px-2 py-1 font-medium">재질</td>
                    {comp.bendingData.map((_, i) => (
                      <td key={i} className="border px-2 py-1 text-center">{comp.material}</td>
                    ))}
                  </tr>
                  <tr>
                    <td className="border px-2 py-1 font-medium">절곡치수</td>
                    {comp.bendingData.map((d) => (
                      <td key={d.no} className={`border px-2 py-1 text-center ${d.color ? 'bg-gray-200 font-bold' : ''}`}>
                        {d.sum}{d.aAngle && <span className="text-red-600 font-bold"> / A°</span>}
                      </td>
                    ))}
                  </tr>
                  <tr>
                    <td className="border px-2 py-1 font-medium">폭합</td>
                    <td className="border px-2 py-1 text-center font-semibold" colSpan={comp.bendingData.length}>
                      {(comp.width_sum || 0).toLocaleString()}
                    </td>
                  </tr>
                  <tr>
                    <td className="border px-2 py-1 font-medium">수량</td>
                    <td className="border px-2 py-1 text-center" colSpan={comp.bendingData.length}>
                      {comp.quantity}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          ))}

          {/* 재질별 폭합 */}
          {components.length > 0 && (
            <div className="border rounded p-3">
              <h4 className="text-sm font-semibold mb-2">재질별 폭합</h4>
              <table className="text-sm border-collapse">
                <thead>
                  <tr className="bg-muted/50">
                    <th className="border px-3 py-1 text-left">재질</th>
                    <th className="border px-3 py-1 text-right">폭합계 (mm)</th>
                  </tr>
                </thead>
                <tbody>
                  {Object.entries(
                    components.reduce((acc, c) => {
                      if (c.material) acc[c.material] = (acc[c.material] || 0) + c.width_sum * c.quantity;
                      return acc;
                    }, {} as Record<string, number>)
                  ).map(([mat, total]) => (
                    <tr key={mat}>
                      <td className="border px-3 py-1">{mat}</td>
                      <td className="border px-3 py-1 text-right font-semibold text-blue-600">{total.toLocaleString()}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </DocumentViewer>

      {/* 그리기 도구 */}
      <DrawingCanvas
        open={isDrawingOpen}
        onOpenChange={setIsDrawingOpen}
        onSave={(imageData) => {
          setDrawingImage(imageData);
          setIsDrawingOpen(false);
        }}
        initialImage={drawingImage || undefined}
        title="결합형태 이미지 그리기"
        description="조립도 형상을 그리거나 편집합니다."
      />

      {/* 삭제 확인 */}
      <DeleteConfirmDialog
        open={isDeleteOpen}
        onOpenChange={setIsDeleteOpen}
        onConfirm={handleDelete}
        loading={isDeleting}
        title={`${cfg.title} 삭제`}
        description={`해당 ${cfg.title}을(를) 삭제하시겠습니까?`}
      />
    </div>
  );
}
