summaryrefslogtreecommitdiff
path: root/lib/rfqs-tech/table/ItemsDialog.tsx
blob: 022d6430de3553531df405efadc07020956fdce0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
"use client"

import * as React from "react"
import { useForm, useFieldArray, useWatch } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"

import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from "@/components/ui/form"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import {
  Command,
  CommandInput,
  CommandList,
  CommandItem,
  CommandGroup,
  CommandEmpty
} from "@/components/ui/command"
import { Check, ChevronsUpDown, Plus, Trash2, Save, X, AlertCircle, Eye } from "lucide-react"
import { toast } from "sonner"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import { Badge } from "@/components/ui/badge"

import { createRfqItem, deleteRfqItem } from "../service"
import { RfqWithItemCount } from "@/db/schema/rfq"      

// Zod 스키마 - 수량은 string으로 받아서 나중에 변환
const itemSchema = z.object({
  id: z.number().optional(),
  itemCode: z.string().nonempty({ message: "아이템 코드를 선택해주세요" }),
  description: z.string().optional(),
  quantity: z.coerce.number().min(1, { message: "최소 수량은 1입니다" }).default(1),
  uom: z.string().default("each"),
});

const itemsFormSchema = z.object({
  rfqId: z.number().int(),
  items: z.array(itemSchema).min(1, { message: "최소 1개 이상의 아이템을 추가해주세요" }),
});

type ItemsFormSchema = z.infer<typeof itemsFormSchema>;

interface RfqsItemsDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  rfq: RfqWithItemCount | null;
  defaultItems?: {
    id?: number;
    itemCode: string;
    quantity?: number | null;
    description?: string | null;
    uom?: string | null;
  }[];
  itemsList: {
    code: string | null;
    itemList?: string;
    subItemList?: string;
  }[];
}

export function RfqsItemsDialog({
  open,
  onOpenChange,
  rfq,
  defaultItems = [],
  itemsList,
}: RfqsItemsDialogProps) {
  const rfqId = rfq?.rfqId ?? 0;
  console.log(itemsList)

  // 편집 가능 여부 확인 - DRAFT 상태일 때만 편집 가능
  const isEditable = rfq?.status === "DRAFT";

  // 초기 아이템 ID 목록을 추적하기 위한 상태 추가
  const [initialItemIds, setInitialItemIds] = React.useState<(number | undefined)[]>([]);

  // 삭제된 아이템 ID를 저장하는 상태 추가
  const [deletedItemIds, setDeletedItemIds] = React.useState<number[]>([]);

  // 1) form
  const form = useForm<ItemsFormSchema>({
    resolver: zodResolver(itemsFormSchema),
    defaultValues: {
      rfqId,
      items: defaultItems.length > 0 ? defaultItems.map((it) => ({
        id: it.id,
        quantity: it.quantity ?? 1,
        uom: it.uom ?? "each",
        itemCode: it.itemCode ?? "",
        description: it.description ?? "",
      })) : [{ itemCode: "", description: "", quantity: 1, uom: "each" }],
    },
    mode: "onChange", // 입력 필드가 변경될 때마다 유효성 검사
  });

  // 다이얼로그가 열릴 때마다 폼 초기화 및 초기 아이템 ID 저장
  React.useEffect(() => {
    if (open) {
      const initialItems = defaultItems.length > 0
        ? defaultItems.map((it) => ({
          id: it.id,
          quantity: it.quantity ?? 1,
          uom: it.uom ?? "each",
          itemCode: it.itemCode ?? "",
          description: it.description ?? "",
        }))
        : [{ itemCode: "", description: "", quantity: 1, uom: "each" }];

      form.reset({
        rfqId,
        items: initialItems,
      });

      // 초기 아이템 ID 목록 저장
      setInitialItemIds(defaultItems.map(item => item.id));

      // 삭제된 아이템 목록 초기화
      setDeletedItemIds([]);
      setHasUnsavedChanges(false);
    }
  }, [open, defaultItems, rfqId, form]);

  // 새로운 요소에 대한 ref 배열
  const inputRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false);
  const [isExitDialogOpen, setIsExitDialogOpen] = React.useState(false);

  // 폼 변경 감지 - 편집 가능한 경우에만 변경 감지
  React.useEffect(() => {
    if (!isEditable) return;

    const subscription = form.watch(() => {
      setHasUnsavedChanges(true);
    });
    return () => subscription.unsubscribe();
  }, [form, isEditable]);

  // 2) field array
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "items",
  });

  // 3) watch items array
  const watchItems = form.watch("items");

  // 4) Add item row with auto-focus
  function handleAddItem() {
    if (!isEditable) return;

    // 명시적으로 숫자 타입으로 지정
    append({
      itemCode: "",
      description: "",
      quantity: 1,
      uom: "each"
    });
    setHasUnsavedChanges(true);

    // 다음 렌더링 사이클에서 새로 추가된 항목에 포커스
    setTimeout(() => {
      const newIndex = fields.length;
      const button = inputRefs.current[newIndex];
      if (button) {
        button.click();
      }
    }, 100);
  }

  // 항목 직접 삭제 - 기존 ID가 있을 경우 삭제 목록에 추가
  const handleRemoveItem = (index: number) => {
    if (!isEditable) return;

    const itemToRemove = form.getValues().items[index];

    // 기존 ID가 있는 아이템이라면 삭제 목록에 추가
    if (itemToRemove.id !== undefined) {
      setDeletedItemIds(prev => [...prev, itemToRemove.id as number]);
    }

    remove(index);
    setHasUnsavedChanges(true);

    // 포커스 처리: 다음 항목이 있으면 다음 항목으로, 없으면 마지막 항목으로
    setTimeout(() => {
      const nextIndex = Math.min(index, fields.length - 1);
      if (nextIndex >= 0 && inputRefs.current[nextIndex]) {
        inputRefs.current[nextIndex]?.click();
      }
    }, 50);
  };

  // 다이얼로그 닫기 전 확인
  const handleDialogClose = (open: boolean) => {
    if (!open && hasUnsavedChanges && isEditable) {
      setIsExitDialogOpen(true);
    } else {
      onOpenChange(open);
    }
  };

  // 필드 포커스 유틸리티 함수
  const focusField = (selector: string) => {
    if (!isEditable) return;

    setTimeout(() => {
      const element = document.querySelector(selector) as HTMLInputElement | null;
      if (element) {
        element.focus();
      }
    }, 10);
  };

  // 5) Submit - 업데이트된 제출 로직 (생성/수정 + 삭제 처리)
  async function onSubmit(data: ItemsFormSchema) {
    if (!isEditable) return;

    try {
      setIsSubmitting(true);

      // 각 아이템이 유효한지 확인 
      const anyInvalidItems = data.items.some(item => !item.itemCode || item.quantity < 1);

      if (anyInvalidItems) {
        toast.error("유효하지 않은 아이템이 있습니다. 모든 필드를 확인해주세요.");
        setIsSubmitting(false);
        return;
      }

      // 1. 삭제 처리 - 삭제된 아이템 ID가 있으면 삭제 요청 
      const deletePromises = deletedItemIds.map(id =>
        deleteRfqItem({
          id: id,
          rfqId: rfqId,
        })
      );

      // 2. 생성/수정 처리 - 폼에 남아있는 아이템들
      const upsertPromises = data.items.map((item) =>
        createRfqItem({
          rfqId: rfqId,
          itemCode: item.itemCode,
          description: item.description,
          // 명시적으로 숫자로 변환
          quantity: Number(item.quantity),
          uom: item.uom,
          id: item.id // 기존 ID가 있으면 업데이트, 없으면 생성
        })
      );

      // 모든 요청 병렬 처리
      await Promise.all([...deletePromises, ...upsertPromises]);

      toast.success("RFQ 아이템이 성공적으로 저장되었습니다!");
      setHasUnsavedChanges(false);
      onOpenChange(false);
    } catch (err) {
      toast.error(`오류가 발생했습니다: ${String(err)}`);
    } finally {
      setIsSubmitting(false);
    }
  }

  // 단축키 처리 - 편집 가능한 경우에만 단축키 활성화
  React.useEffect(() => {
    if (!isEditable) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      // Alt+N: 새 항목 추가
      if (e.altKey && e.key === 'n') {
        e.preventDefault();
        handleAddItem();
      }
      // Ctrl+S: 저장
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        form.handleSubmit(onSubmit)();
      }
      // Esc: 포커스된 팝오버 닫기
      if (e.key === 'Escape') {
        document.querySelectorAll('[role="combobox"][aria-expanded="true"]').forEach(
          (el) => (el as HTMLButtonElement).click()
        );
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [form, isEditable]);

  return (
    <>
      <Dialog open={open} onOpenChange={handleDialogClose}>
        <DialogContent className="max-w-none w-[1200px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {isEditable ? "RFQ 아이템 관리" : "RFQ 아이템 조회"}
              <Badge variant="outline" className="ml-2">
                {rfq?.rfqCode || `RFQ #${rfqId}`}
              </Badge>
             
              {rfq?.status && (
                <Badge
                  variant={rfq.status === "DRAFT" ? "outline" : "secondary"}
                  className="ml-1"
                >
                  {rfq.status}
                </Badge>
              )}
            </DialogTitle>
            <DialogDescription>
              {isEditable
                ? (rfq?.description || '아이템을 각 행에 하나씩 추가할 수 있습니다.')
                : '드래프트 상태가 아닌 RFQ는 아이템을 편집할 수 없습니다.'}
            </DialogDescription>
          </DialogHeader>
          <div className="overflow-x-auto w-full">
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)}>
                <div className="space-y-4">
                  {/* 헤더 행 (라벨) */}
                  <div className="flex items-center gap-2 border-b pb-2 font-medium text-sm">
                    <div className="w-[250px] pl-3">아이템</div>
                    <div className="w-[400px] pl-2">설명</div>
                    <div className="w-[80px] pl-2 text-center">수량</div>
                    <div className="w-[80px] pl-2 text-center">단위</div>
                    {isEditable && <div className="w-[42px]"></div>}
                  </div>

                  {/* 아이템 행들 */}
                  <div className="max-h-[50vh] overflow-y-auto pr-1 space-y-3">
                    {fields.map((field, index) => {
                      // 현재 row의 itemCode
                      const codeValue = watchItems[index]?.itemCode || "";
                      // "이미" 사용된 코드를 모두 구함
                      const usedCodes = watchItems
                        .map((it, i) => i === index ? null : it.itemCode)
                        .filter(Boolean) as string[];

                      // itemsList에서 "현재 선택한 code"만 예외적으로 허용하고,
                      // 다른 행에서 이미 사용한 code는 제거
                      const filteredItems = (itemsList || [])
                        .filter((it) => {
                          if (!it.code) return false;
                          if (it.code === codeValue) return true;
                          return !usedCodes.includes(it.code);
                        });

                      // 선택된 아이템 찾기
                      const selected = filteredItems.find(it => it.code === codeValue);

                      return (
                        <div key={field.id} className="flex items-center gap-2 group hover:bg-gray-50 p-1 rounded-md transition-colors">
                          {/* -- itemCode + Popover(Select) -- */}
                          {isEditable ? (
                            <FormField
                              control={form.control}
                              name={`items.${index}.itemCode`}
                              render={({ field }) => {
                                const [popoverOpen, setPopoverOpen] = React.useState(false);
                                const selected = filteredItems.find(it => it.code === field.value);

                                return (
                                  <FormItem className="flex items-center gap-2 w-[250px]" style={{width:250}}>
                                    <FormControl>
                                      <Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
                                        <PopoverTrigger asChild>
                                          <Button
                                            ref={el => {
                                              inputRefs.current[index] = el;
                                            }}
                                            variant="outline"
                                            role="combobox"
                                            aria-expanded={popoverOpen}
                                            className="flex items-center"
                                            data-error={!!form.formState.errors.items?.[index]?.itemCode}
                                            data-state={selected ? "filled" : "empty"}
                                            style={{width:250}}
                                          >
                                            <div className="flex-1 overflow-hidden mr-2 text-left">
                                              <span className="block truncate" style={{width:200}}>
                                                {selected ? (
                                                  <>
                                                    <div>{selected.code}</div>
                                                    {(selected.itemList || selected.subItemList) && (
                                                      <div className="text-xs text-muted-foreground">
                                                        {selected.itemList}
                                                        {selected.subItemList && ` / ${selected.subItemList}`}
                                                      </div>
                                                    )}
                                                  </>
                                                ) : "아이템 선택..."}
                                              </span>
                                            </div>
                                            <ChevronsUpDown className="h-4 w-4 flex-shrink-0 opacity-50" />
                                          </Button>
                                        </PopoverTrigger>
                                        <PopoverContent className="w-[400px] p-0">
                                          <Command>
                                            <CommandInput placeholder="아이템 검색..." className="h-9" autoFocus />
                                            <CommandList>
                                              <CommandEmpty>아이템을 찾을 수 없습니다.</CommandEmpty>
                                              <CommandGroup>
                                                {filteredItems.map((it) => (
                                                  <CommandItem
                                                    key={it.code}
                                                    value={`${it.code} ${it.itemList || ''} ${it.subItemList || ''}`}
                                                    onSelect={() => {
                                                      field.onChange(it.code);
                                                      setPopoverOpen(false);
                                                      focusField(`input[name="items.${index}.description"]`);
                                                    }}
                                                  >
                                                    <div className="flex-1 overflow-hidden">
                                                      <div className="font-medium">{it.code}</div>
                                                      {(it.itemList || it.subItemList) && (
                                                        <div className="text-xs text-muted-foreground">
                                                          {it.itemList}
                                                          {it.subItemList && ` / ${it.subItemList}`}
                                                        </div>
                                                      )}
                                                    </div>
                                                    <Check
                                                      className={
                                                        "ml-auto h-4 w-4" +
                                                        (it.code === field.value ? " opacity-100" : " opacity-0")
                                                      }
                                                    />
                                                  </CommandItem>
                                                ))}
                                              </CommandGroup>
                                            </CommandList>
                                          </Command>
                                        </PopoverContent>
                                      </Popover>
                                    </FormControl>
                                    {form.formState.errors.items?.[index]?.itemCode && (
                                      <AlertCircle className="h-4 w-4 text-destructive" />
                                    )}
                                  </FormItem>
                                );
                              }}
                            />
                          ) : (
                            <div className="flex items-center w-[250px] pl-3">
                              {selected ? `${selected.code}` : codeValue}
                            </div>
                          )}

                          {/* ID 필드 추가 (숨김) */}
                          <FormField
                            control={form.control}
                            name={`items.${index}.id`}
                            render={({ field }) => (
                              <input type="hidden" {...field} />
                            )}
                          />

                          {/* description */}
                          {isEditable ? (
                            <FormField
                              control={form.control}
                              name={`items.${index}.description`}
                              render={({ field }) => (
                                <FormItem className="w-[400px]">
                                  <FormControl>
                                    <Input
                                      className="w-full"
                                      placeholder="아이템 상세 정보"
                                      {...field}
                                      onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                          e.preventDefault();
                                          focusField(`input[name="items.${index}.quantity"]`);
                                        }
                                      }}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          ) : (
                            <div className="w-[400px] pl-2">
                              {watchItems[index]?.description || ""}
                            </div>
                          )}

                          {/* quantity */}
                          {isEditable ? (
                            <FormField
                              control={form.control}
                              name={`items.${index}.quantity`}
                              render={({ field }) => (
                                <FormItem className="w-[80px] relative">
                                  <FormControl>
                                    <Input
                                      type="number"
                                      className="w-full text-center"
                                      min="1"
                                      {...field}
                                      // 값 변경 핸들러 개선
                                      onChange={(e) => {
                                        const value = e.target.value === '' ? 1 : parseInt(e.target.value, 10);
                                        field.onChange(isNaN(value) ? 1 : value);
                                      }}
                                      // 최소값 보장 (빈 문자열 방지)
                                      onBlur={(e) => {
                                        if (e.target.value === '' || parseInt(e.target.value, 10) < 1) {
                                          field.onChange(1);
                                        }
                                      }}
                                      onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                          e.preventDefault();
                                          focusField(`input[name="items.${index}.uom"]`);
                                        }
                                      }}
                                    />
                                  </FormControl>
                                  {form.formState.errors.items?.[index]?.quantity && (
                                    <AlertCircle className="h-4 w-4 text-destructive absolute right-2 top-2" />
                                  )}
                                </FormItem>
                              )}
                            />
                          ) : (
                            <div className="w-[80px] text-center">
                              {watchItems[index]?.quantity}
                            </div>
                          )}

                          {/* uom */}
                          {isEditable ? (
                            <FormField
                              control={form.control}
                              name={`items.${index}.uom`}
                              render={({ field }) => (
                                <FormItem className="w-[80px]">
                                  <FormControl>
                                    <Input
                                      placeholder="each"
                                      className="w-full text-center"
                                      {...field}
                                      onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                          e.preventDefault();
                                          // 마지막 행이면 새로운 행 추가
                                          if (index === fields.length - 1) {
                                            handleAddItem();
                                          } else {
                                            // 아니면 다음 행의 아이템 선택으로 이동
                                            const button = inputRefs.current[index + 1];
                                            if (button) {
                                              setTimeout(() => button.click(), 10);
                                            }
                                          }
                                        }
                                      }}
                                    />
                                  </FormControl>
                                  <FormMessage />
                                </FormItem>
                              )}
                            />
                          ) : (
                            <div className="w-[80px] text-center">
                              {watchItems[index]?.uom || "each"}
                            </div>
                          )}

                          {/* remove row - 편집 모드에서만 표시 */}
                          {isEditable && (
                            <TooltipProvider>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => handleRemoveItem(index)}
                                    className="group-hover:opacity-100 transition-opacity"
                                    aria-label="아이템 삭제"
                                  >
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent>
                                  <p>아이템 삭제</p>
                                </TooltipContent>
                              </Tooltip>
                            </TooltipProvider>
                          )}
                        </div>
                      );
                    })}
                  </div>

                  <div className="flex justify-between items-center pt-2 border-t">
                    <div className="flex items-center gap-2">
                      {isEditable ? (
                        <>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <Button type="button" variant="outline" onClick={handleAddItem} className="gap-1">
                                  <Plus className="h-4 w-4" />
                                  아이템 추가
                                </Button>
                              </TooltipTrigger>
                              <TooltipContent side="bottom">
                                <p>단축키: Alt+N</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                          <span className="text-sm text-muted-foreground">
                            {fields.length}개 아이템
                          </span>
                          {deletedItemIds.length > 0 && (
                            <span className="text-sm text-destructive">
                              ({deletedItemIds.length}개 아이템 삭제 예정)
                            </span>
                          )}
                        </>
                      ) : (
                        <span className="text-sm text-muted-foreground">
                          {fields.length}개 아이템
                        </span>
                      )}
                    </div>

                    {isEditable && (
                      <div className="text-xs text-muted-foreground">
                        <span className="inline-flex items-center gap-1 mr-2">
                          <kbd className="px-1 py-0.5 bg-gray-100 rounded text-xs">Tab</kbd>
                          <span>필드 간 이동</span>
                        </span>
                        <span className="inline-flex items-center gap-1">
                          <kbd className="px-1 py-0.5 bg-gray-100 rounded text-xs">Enter</kbd>
                          <span>다음 필드로 이동</span>
                        </span>
                      </div>
                    )}
                  </div>
                </div>

                <DialogFooter className="mt-6 gap-2">
                  {isEditable ? (
                    <>
                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button type="button" variant="outline" onClick={() => handleDialogClose(false)}>
                              <X className="mr-2 h-4 w-4" />
                              취소
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>변경사항을 저장하지 않고 나가기</TooltipContent>
                        </Tooltip>
                      </TooltipProvider>

                      <TooltipProvider>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              type="submit"
                              disabled={isSubmitting || (!form.formState.isDirty && deletedItemIds.length === 0) || !form.formState.isValid}
                            >
                              {isSubmitting ? (
                                <>처리 중...</>
                              ) : (
                                <>
                                  <Save className="mr-2 h-4 w-4" />
                                  저장
                                </>
                              )}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>
                            <p>단축키: Ctrl+S</p>
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    </>
                  ) : (
                    <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                      <X className="mr-2 h-4 w-4" />
                      닫기
                    </Button>
                  )}
                </DialogFooter>
              </form>
            </Form>
          </div>
        </DialogContent>
      </Dialog>

      {/* 저장하지 않고 나가기 확인 다이얼로그 - 편집 모드에서만 활성화 */}
      {isEditable && (
        <AlertDialog open={isExitDialogOpen} onOpenChange={setIsExitDialogOpen}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>저장되지 않은 변경사항</AlertDialogTitle>
              <AlertDialogDescription>
                저장되지 않은 변경사항이 있습니다. 그래도 나가시겠습니까?
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>취소</AlertDialogCancel>
              <AlertDialogAction onClick={() => {
                setIsExitDialogOpen(false);
                onOpenChange(false);
              }}>
                저장하지 않고 나가기
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      )}
    </>
  );
}