'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { Drawer, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerTitle } from '@/components/ui/drawer';
import { Plus, X, Edit, Trash2, Check } from 'lucide-react';
import { toast } from 'sonner';
import type { ItemPage, ItemSection, ItemMasterField } from '@/contexts/ItemMasterContext';

interface OptionColumn {
  id: string;
  name: string;
  key: string;
}

const INPUT_TYPE_OPTIONS = [
  { value: 'textbox', label: '텍스트박스' },
  { value: 'dropdown', label: '드롭다운' },
  { value: 'checkbox', label: '체크박스' },
  { value: 'number', label: '숫자' },
  { value: 'date', label: '날짜' },
  { value: 'textarea', label: '텍스트영역' }
];

// 유연한 조건부 필드 타입
interface FlexibleConditionField {
  fieldId?: string;
  fieldKey?: string;
  fieldName?: string;
  operator?: string;
  value?: string;
  expectedValue?: string;
  logicOperator?: 'AND' | 'OR';
}

// 유연한 조건부 섹션 타입
interface FlexibleConditionSection {
  sectionId?: string;
  sectionTitle?: string;
  operator?: string;
  value?: string;
  logicOperator?: 'AND' | 'OR';
}

// 입력 모드 타입: 'new'/'existing' 또는 'custom'/'master' 모두 지원
type FieldInputModeType = 'new' | 'existing' | 'custom' | 'master';

interface FieldDrawerProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  editingFieldId: number | null;
  setEditingFieldId: (id: number | null) => void;
  // 'new'/'existing' 또는 'custom'/'master' 모두 지원
  fieldInputMode: FieldInputModeType;
  setFieldInputMode: (mode: FieldInputModeType) => void;
  showMasterFieldList: boolean;
  setShowMasterFieldList: (show: boolean) => void;
  // string 또는 number | null 모두 지원
  selectedMasterFieldId: string | number | null;
  setSelectedMasterFieldId: (id: string | number | null) => void;
  textboxColumns: OptionColumn[];
  setTextboxColumns: React.Dispatch<React.SetStateAction<OptionColumn[]>>;
  newFieldConditionEnabled: boolean;
  setNewFieldConditionEnabled: (enabled: boolean) => void;
  newFieldConditionTargetType: 'field' | 'section';
  setNewFieldConditionTargetType: (type: 'field' | 'section') => void;
  // 유연한 조건부 필드 타입
  newFieldConditionFields: FlexibleConditionField[] | Array<{ fieldKey: string; expectedValue: string }>;
  setNewFieldConditionFields: React.Dispatch<React.SetStateAction<FlexibleConditionField[]>> | React.Dispatch<React.SetStateAction<Array<{ fieldKey: string; expectedValue: string }>>>;
  // 유연한 조건부 섹션 타입
  newFieldConditionSections: string[] | FlexibleConditionSection[];
  setNewFieldConditionSections: React.Dispatch<React.SetStateAction<string[]>> | React.Dispatch<React.SetStateAction<FlexibleConditionSection[]>>;
  tempConditionValue: string;
  setTempConditionValue: (value: string) => void;
  newFieldName: string;
  setNewFieldName: (name: string) => void;
  newFieldKey: string;
  setNewFieldKey: (key: string) => void;
  // string 타입으로 유연하게 처리
  newFieldInputType: string;
  setNewFieldInputType: (type: string) => void;
  newFieldRequired: boolean;
  setNewFieldRequired: (required: boolean) => void;
  newFieldDescription: string;
  setNewFieldDescription: (description: string) => void;
  // string | string[] 모두 지원
  newFieldOptions: string | string[];
  setNewFieldOptions: ((options: string) => void) | React.Dispatch<React.SetStateAction<string[]>>;
  selectedSectionForField: ItemSection | null;
  selectedPage: ItemPage | null;
  itemMasterFields: ItemMasterField[];
  handleAddField: () => void | Promise<void>;
  setIsColumnDialogOpen: (open: boolean) => void;
  setEditingColumnId: (id: string | null) => void;
  setColumnName: (name: string) => void;
  setColumnKey: (key: string) => void;
}

export function FieldDrawer({
  isOpen,
  onOpenChange,
  editingFieldId,
  setEditingFieldId,
  fieldInputMode,
  setFieldInputMode,
  showMasterFieldList,
  setShowMasterFieldList,
  selectedMasterFieldId,
  setSelectedMasterFieldId,
  textboxColumns,
  setTextboxColumns,
  newFieldConditionEnabled,
  setNewFieldConditionEnabled,
  newFieldConditionTargetType,
  setNewFieldConditionTargetType,
  newFieldConditionFields,
  setNewFieldConditionFields,
  newFieldConditionSections,
  setNewFieldConditionSections,
  tempConditionValue,
  setTempConditionValue,
  newFieldName,
  setNewFieldName,
  newFieldKey,
  setNewFieldKey,
  newFieldInputType,
  setNewFieldInputType,
  newFieldRequired,
  setNewFieldRequired,
  newFieldDescription,
  setNewFieldDescription,
  newFieldOptions,
  setNewFieldOptions,
  selectedSectionForField,
  selectedPage,
  itemMasterFields,
  handleAddField,
  setIsColumnDialogOpen,
  setEditingColumnId,
  setColumnName,
  setColumnKey
}: FieldDrawerProps) {
  // 입력 모드 정규화: 'new' → 'custom', 'existing' → 'master'
  const normalizedInputMode =
    fieldInputMode === 'new' ? 'custom' :
    fieldInputMode === 'existing' ? 'master' :
    fieldInputMode;

  const isCustomMode = normalizedInputMode === 'custom';
  const isMasterMode = normalizedInputMode === 'master';

  // 옵션을 문자열로 변환하여 처리
  const optionsString = Array.isArray(newFieldOptions) ? newFieldOptions.join(', ') : newFieldOptions;

  // setNewFieldOptions 래퍼 - union type 호환성 해결
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleSetNewFieldOptions = (options: string) => (setNewFieldOptions as any)(options);

  // setNewFieldConditionFields 래퍼 - union type 호환성 해결
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleSetNewFieldConditionFields = (updater: any) => (setNewFieldConditionFields as any)(updater);

  // setNewFieldConditionSections 래퍼 - union type 호환성 해결
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleSetNewFieldConditionSections = (updater: any) => (setNewFieldConditionSections as any)(updater);

  const handleClose = () => {
    onOpenChange(false);
    setEditingFieldId(null);
    setFieldInputMode('custom');
    setShowMasterFieldList(false);
    setSelectedMasterFieldId('');
    setTextboxColumns([]);
    setNewFieldConditionEnabled(false);
    setNewFieldConditionTargetType('field');
    setNewFieldConditionFields([]);
    setNewFieldConditionSections([]);
    setTempConditionValue('');
  };

  return (
    <Drawer open={isOpen} onOpenChange={handleClose}>
      <DrawerContent className="max-h-[90vh] flex flex-col">
        <DrawerHeader className="px-4 py-3 border-b">
          <DrawerTitle>{editingFieldId ? '항목 수정' : '항목 추가'}</DrawerTitle>
          <DrawerDescription>
            재사용 가능한 항목을 선택하거나 직접 입력하세요
          </DrawerDescription>
        </DrawerHeader>

        <div className="flex-1 overflow-y-auto px-4 py-4 space-y-4">
          {/* 입력 모드 선택 (편집 시에는 표시 안 함) */}
          {!editingFieldId && (
            <div className="flex gap-2 p-1 bg-gray-100 rounded">
              <Button
                variant={isCustomMode ? 'default' : 'ghost'}
                size="sm"
                onClick={() => setFieldInputMode('custom')}
                className="flex-1"
              >
                직접 입력
              </Button>
              <Button
                variant={isMasterMode ? 'default' : 'ghost'}
                size="sm"
                onClick={() => {
                  setFieldInputMode('master');
                  setShowMasterFieldList(true);
                }}
                className="flex-1"
              >
                항목 선택
              </Button>
            </div>
          )}

          {/* 항목 목록 */}
          {isMasterMode && !editingFieldId && showMasterFieldList && (
            <div className="border rounded p-3 space-y-2 max-h-[400px] overflow-y-auto">
              <div className="flex items-center justify-between mb-2">
                <Label>항목 목록</Label>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setShowMasterFieldList(false)}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
              {itemMasterFields.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-4">
                  등록된 항목이 없습니다
                </p>
              ) : (
                <div className="space-y-2">
                  {itemMasterFields.map((field, index) => (
                    <div
                      key={`drawer-${field.id}-${index}`}
                      className={`p-3 border rounded cursor-pointer transition-colors ${
                        selectedMasterFieldId === String(field.id)
                          ? 'bg-blue-50 border-blue-300'
                          : 'hover:bg-gray-50'
                      }`}
                      onClick={() => {
                        setSelectedMasterFieldId(String(field.id));
                        setNewFieldName(field.field_name);
                        setNewFieldKey(`field_${field.id}`);
                        setNewFieldInputType(field.field_type);
                        setNewFieldRequired((field.properties as any)?.required ?? false);
                        setNewFieldDescription(field.description || '');
                        handleSetNewFieldOptions(field.options?.map(o => o.value).join(', ') || '');
                        const props = field.properties as any;
                        if (props?.multiColumn && props?.columnNames) {
                          setTextboxColumns(
                            props.columnNames.map((name: string, idx: number) => ({
                              id: `col-${idx}`,
                              name,
                              key: `column${idx + 1}`
                            }))
                          );
                        }
                      }}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <span className="font-medium">{field.field_name}</span>
                            <Badge variant="outline" className="text-xs">
                              {INPUT_TYPE_OPTIONS.find(o => o.value === field.field_type)?.label}
                            </Badge>
                            {(field.properties as any)?.required && (
                              <Badge variant="destructive" className="text-xs">필수</Badge>
                            )}
                          </div>
                          {field.description && (
                            <p className="text-xs text-muted-foreground mt-1">{field.description}</p>
                          )}
                          {field.category && (
                            <div className="flex gap-1 mt-1">
                              <Badge variant="secondary" className="text-xs">
                                {field.category}
                              </Badge>
                            </div>
                          )}
                        </div>
                        {selectedMasterFieldId === String(field.id) && (
                          <Check className="h-5 w-5 text-blue-600" />
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* 직접 입력 폼 */}
          {(isCustomMode || editingFieldId) && (
            <>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label>항목명 *</Label>
                  <Input
                    value={newFieldName}
                    onChange={(e) => setNewFieldName(e.target.value)}
                    placeholder="예: 품목명"
                  />
                </div>
                <div>
                  <Label>필드 키 *</Label>
                  <Input
                    value={newFieldKey}
                    onChange={(e) => setNewFieldKey(e.target.value)}
                    placeholder="예: itemName"
                  />
                </div>
              </div>

              <div>
                <Label>입력방식 *</Label>
                <Select value={newFieldInputType} onValueChange={(v: any) => setNewFieldInputType(v)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {INPUT_TYPE_OPTIONS.map(opt => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {newFieldInputType === 'dropdown' && (
                <div>
                  <Label>드롭다운 옵션</Label>
                  <Input
                    value={optionsString}
                    onChange={(e) => handleSetNewFieldOptions(e.target.value)}
                    placeholder="옵션1, 옵션2, 옵션3 (쉼표로 구분)"
                  />
                </div>
              )}

              {/* 텍스트박스 컬럼 관리 */}
              {newFieldInputType === 'textbox' && (
                <div className="border rounded p-3 space-y-3">
                  <div className="flex items-center justify-between">
                    <Label>텍스트박스 컬럼 관리</Label>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setIsColumnDialogOpen(true);
                        setEditingColumnId(null);
                        setColumnName('');
                        setColumnKey('');
                      }}
                    >
                      <Plus className="h-4 w-4 mr-1" />
                      컬럼 추가
                    </Button>
                  </div>
                  {textboxColumns.length > 0 ? (
                    <div className="space-y-2">
                      {textboxColumns.map((col, index) => (
                        <div key={col.id} className="flex items-center gap-2 p-2 bg-gray-50 rounded">
                          <span className="text-sm flex-1">
                            {index + 1}. {col.name} ({col.key})
                          </span>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setEditingColumnId(col.id);
                              setColumnName(col.name);
                              setColumnKey(col.key);
                              setIsColumnDialogOpen(true);
                            }}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setTextboxColumns(prev => prev.filter(c => c.id !== col.id));
                              toast.success('컬럼이 삭제되었습니다');
                            }}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <p className="text-sm text-muted-foreground text-center py-2">
                      추가된 컬럼이 없습니다
                    </p>
                  )}
                </div>
              )}

              <div>
                <Label>설명 (선택)</Label>
                <Textarea
                  value={newFieldDescription}
                  onChange={(e) => setNewFieldDescription(e.target.value)}
                  placeholder="항목에 대한 설명"
                />
              </div>

              <div className="flex items-center gap-2">
                <Switch checked={newFieldRequired} onCheckedChange={setNewFieldRequired} />
                <Label>필수 항목</Label>
              </div>
            </>
          )}

          {/* 조건부 표시 설정 - 모든 입력방식에서 사용 가능 */}
          {(isCustomMode || editingFieldId) && (
            <div className="border-t pt-4 space-y-3">
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <Switch checked={newFieldConditionEnabled} onCheckedChange={setNewFieldConditionEnabled} />
                  <Label className="text-base">조건부 표시 설정</Label>
                </div>
                <p className="text-xs text-muted-foreground pl-8">
                  이 항목의 값에 따라 다른 항목이나 섹션을 동적으로 표시/숨김 처리합니다 (모든 입력방식 지원)
                </p>
              </div>

              {newFieldConditionEnabled && selectedSectionForField && (
                <div className="space-y-4 pl-6 pt-3 border-l-2 border-blue-200">
                  {/* 대상 타입 선택 */}
                  <div className="space-y-2 bg-blue-50 p-3 rounded">
                    <Label className="text-sm font-semibold">조건이 성립하면 무엇을 표시할까요?</Label>
                    <div className="flex gap-4 pl-2">
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="radio"
                          checked={newFieldConditionTargetType === 'field'}
                          onChange={() => setNewFieldConditionTargetType('field')}
                          className="cursor-pointer"
                        />
                        <span className="text-sm">추가 항목들 (이후 추가할 항목들에 조건 연결)</span>
                      </label>
                      <label className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="radio"
                          checked={newFieldConditionTargetType === 'section'}
                          onChange={() => setNewFieldConditionTargetType('section')}
                          className="cursor-pointer"
                        />
                        <span className="text-sm">전체 섹션</span>
                      </label>
                    </div>
                  </div>

                  {/* 일반항목용 조건 설정 */}
                  {newFieldConditionTargetType === 'field' && (
                    <div className="space-y-3">
                      <div className="bg-yellow-50 p-3 rounded border border-yellow-200">
                        <p className="text-xs text-yellow-800">
                          <strong>💡 사용 방법:</strong><br/>
                          1. 아래에서 조건값(예: "제품", "원자재")을 추가합니다<br/>
                          2. 이 항목을 저장한 후, 같은 섹션에 다른 항목을 추가할 때<br/>
                          3. 새 항목의 "조건부 표시" 설정에서 이 항목과 조건값을 선택하면<br/>
                          4. 조건이 맞을 때만 해당 항목이 표시됩니다
                        </p>
                      </div>

                      <div>
                        <Label className="text-sm font-semibold">조건값 목록 (이 항목의 어떤 값일 때 다른 항목을 표시할지)</Label>
                        <p className="text-xs text-muted-foreground mt-1">
                          {newFieldInputType === 'dropdown' && '드롭다운 옵션값을 입력하세요'}
                          {newFieldInputType === 'checkbox' && '체크박스 상태값(true/false)을 입력하세요'}
                          {newFieldInputType === 'textbox' && '텍스트 값을 입력하세요 (예: "제품", "부품")'}
                          {newFieldInputType === 'number' && '숫자 값을 입력하세요 (예: 100, 200)'}
                          {newFieldInputType === 'date' && '날짜 값을 입력하세요 (예: 2025-01-01)'}
                          {newFieldInputType === 'textarea' && '텍스트 값을 입력하세요'}
                        </p>
                      </div>

                      {/* 추가된 조건 목록 */}
                      {newFieldConditionFields.length > 0 && (
                        <div className="space-y-2">
                          {newFieldConditionFields.map((condition, index) => (
                            <div key={index} className="flex items-center gap-2 p-3 bg-blue-50 rounded border border-blue-200">
                              <div className="flex-1">
                                <span className="text-sm font-medium text-blue-900">
                                  값이 "{condition.expectedValue}"일 때
                                </span>
                                <p className="text-xs text-blue-700 mt-1">
                                  → 이 조건에 연결된 항목들이 표시됩니다
                                </p>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => {
                                  handleSetNewFieldConditionFields((prev: FlexibleConditionField[]) => prev.filter((_: FlexibleConditionField, i: number) => i !== index));
                                  toast.success('조건이 제거되었습니다.');
                                }}
                                className="h-8 w-8 p-0"
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </div>
                          ))}
                        </div>
                      )}

                      {/* 새 조건 추가 */}
                      <div className="flex gap-2">
                        <Input
                          value={tempConditionValue}
                          onChange={(e) => setTempConditionValue(e.target.value)}
                          placeholder={
                            newFieldInputType === 'dropdown' ? "예: 제품, 부품, 원자재..." :
                            newFieldInputType === 'checkbox' ? "예: true 또는 false" :
                            newFieldInputType === 'number' ? "예: 100" :
                            newFieldInputType === 'date' ? "예: 2025-01-01" :
                            "예: 값을 입력하세요"
                          }
                          className="flex-1"
                        />
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            if (tempConditionValue) {
                              handleSetNewFieldConditionFields((prev: FlexibleConditionField[]) => [...prev, {
                                fieldKey: newFieldKey, // 현재 항목 자신의 키를 사용
                                expectedValue: tempConditionValue
                              }]);
                              setTempConditionValue('');
                              toast.success('조건값이 추가되었습니다.');
                            } else {
                              toast.error('조건값을 입력해주세요.');
                            }
                          }}
                        >
                          <Plus className="h-4 w-4 mr-1" />
                          조건 추가
                        </Button>
                      </div>
                    </div>
                  )}

                  {/* 섹션용 조건 설정 */}
                  {newFieldConditionTargetType === 'section' && selectedPage && (
                    <div className="space-y-3">
                      <div className="bg-yellow-50 p-3 rounded border border-yellow-200">
                        <p className="text-xs text-yellow-800">
                          <strong>💡 사용 방법:</strong><br/>
                          1. 먼저 조건값을 추가합니다 (예: "제품", "부품")<br/>
                          2. 각 조건값일 때 표시할 섹션들을 선택합니다<br/>
                          3. 사용자가 이 항목에서 값을 선택하면 해당 섹션이 자동으로 표시/숨김 됩니다
                        </p>
                      </div>

                      {/* 조건값 추가 */}
                      <div>
                        <Label className="text-sm font-semibold">조건값 목록</Label>
                        <div className="flex gap-2 mt-2">
                          <Input
                            value={tempConditionValue}
                            onChange={(e) => setTempConditionValue(e.target.value)}
                            placeholder={
                              newFieldInputType === 'dropdown' ? "예: 제품, 부품, 원자재..." :
                              newFieldInputType === 'checkbox' ? "예: true 또는 false" :
                              newFieldInputType === 'number' ? "예: 100" :
                              newFieldInputType === 'date' ? "예: 2025-01-01" :
                              "예: 값을 입력하세요"
                            }
                            className="flex-1"
                          />
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => {
                              if (tempConditionValue) {
                                if (!newFieldConditionFields.find(f => f.expectedValue === tempConditionValue)) {
                                  handleSetNewFieldConditionFields((prev: FlexibleConditionField[]) => [...prev, {
                                    fieldKey: newFieldKey,
                                    expectedValue: tempConditionValue
                                  }]);
                                  setTempConditionValue('');
                                  toast.success('조건값이 추가되었습니다.');
                                } else {
                                  toast.error('이미 추가된 조건값입니다.');
                                }
                              } else {
                                toast.error('조건값을 입력해주세요.');
                              }
                            }}
                          >
                            <Plus className="h-4 w-4 mr-1" />
                            추가
                          </Button>
                        </div>
                      </div>

                      {/* 조건값 목록 표시 */}
                      {newFieldConditionFields.length > 0 && (
                        <div className="space-y-2">
                          <Label className="text-xs text-muted-foreground">추가된 조건값:</Label>
                          <div className="flex flex-wrap gap-2">
                            {newFieldConditionFields.map((condition, index) => (
                              <Badge key={index} variant="secondary" className="gap-1">
                                {condition.expectedValue}
                                <button
                                  onClick={() => {
                                    handleSetNewFieldConditionFields((prev: FlexibleConditionField[]) => prev.filter((_: FlexibleConditionField, i: number) => i !== index));
                                    toast.success('조건값이 제거되었습니다.');
                                  }}
                                  className="ml-1 hover:text-red-500"
                                >
                                  <X className="h-3 w-3" />
                                </button>
                              </Badge>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* 섹션 선택 */}
                      <div className="space-y-2">
                        <Label className="text-sm font-semibold">조건값에 관계없이 표시할 섹션들 선택:</Label>
                        <p className="text-xs text-muted-foreground">
                          위 조건값 중 하나라도 선택되면 아래 섹션들이 표시됩니다
                        </p>
                        <div className="space-y-2 max-h-60 overflow-y-auto">
                          {selectedPage.sections
                            .filter(section => section.section_type !== 'BOM')
                            .map(section => (
                              <label key={section.id} className="flex items-center gap-2 p-2 bg-muted rounded cursor-pointer hover:bg-muted/80">
                                <input
                                  type="checkbox"
                                  checked={newFieldConditionSections.includes(String(section.id))}
                                  onChange={(e) => {
                                    const sectionIdStr = String(section.id);
                                    if (e.target.checked) {
                                      handleSetNewFieldConditionSections((prev: string[]) => [...prev, sectionIdStr]);
                                    } else {
                                      handleSetNewFieldConditionSections((prev: string[]) => prev.filter((id: string) => id !== sectionIdStr));
                                    }
                                  }}
                                  className="cursor-pointer"
                                />
                                <span className="flex-1 text-sm">{section.title}</span>
                              </label>
                            ))}
                        </div>
                        {newFieldConditionSections.length > 0 && (
                          <div className="text-sm text-blue-600 font-medium mt-2">
                            ✓ {newFieldConditionSections.length}개 섹션이 조건부로 표시됩니다
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        <DrawerFooter className="px-4 py-3 border-t flex-row gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)} className="flex-1">취소</Button>
          <Button onClick={async () => await handleAddField()} className="flex-1">저장</Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  );
}
