import { useState, useEffect } from 'react';
import { PageLayout } from './organisms/PageLayout';
import { PageHeader } from './organisms/PageHeader';
import { useData } from './contexts/DataContext';
import type { ItemPage, ItemSection, ItemField, FieldDisplayCondition, ItemMasterField, ItemFieldProperty } from './contexts/DataContext';
import { 
  Database, 
  Plus, 
  Trash2, 
  ChevronRight, 
  ChevronDown,
  FolderTree,
  Folder,
  FileText,
  Settings,
  ListTree,
  Save,
  X,
  GripVertical,
  Eye,
  EyeOff,
  Edit,
  Check
} from 'lucide-react';
import { DraggableField } from './DraggableField';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import { Textarea } from './ui/textarea';
import { Switch } from './ui/switch';
import { Badge } from './ui/badge';
import { 
  Dialog, 
  DialogContent, 
  DialogDescription, 
  DialogFooter, 
  DialogHeader, 
  DialogTitle 
} from './ui/dialog';
import { toast } from 'sonner@2.0.3';
import { SpecificationManagement } from './SpecificationManagement';

// 로컬스토리지 키
const UNIT_OPTIONS_KEY = 'unit-options';
const MATERIAL_OPTIONS_KEY = 'material-options';
const SURFACE_TREATMENT_OPTIONS_KEY = 'surface-treatment-options';
const ITEM_CLASSIFICATIONS_KEY = 'item-classifications';

// 옵션 타입
interface MasterOption {
  id: string;
  value: string;
  label: string;
  isActive: boolean;
}

// 품목분류 타입
interface ItemClassification {
  id: string;
  name: string;
  description?: string;
  fieldIds: string[]; // 이 분류에 포함된 항목(필드) ID 목록
  isActive: boolean;
  createdAt: string;
}

// 초기 데이터

const INITIAL_UNIT_OPTIONS: MasterOption[] = [
  { id: 'unit-1', value: 'EA', label: 'EA (개)', isActive: true },
  { id: 'unit-2', value: 'SET', label: 'SET (세트)', isActive: true },
];

const INITIAL_MATERIAL_OPTIONS: MasterOption[] = [
  { id: 'mat-1', value: 'EGI 1.2T', label: 'EGI 1.2T', isActive: true },
  { id: 'mat-2', value: 'SUS 1.2T', label: 'SUS 1.2T', isActive: true },
];

const INITIAL_SURFACE_TREATMENT_OPTIONS: MasterOption[] = [
  { id: 'surf-1', value: '무도장', label: '무도장', isActive: true },
  { id: 'surf-2', value: '파우더도장', label: '파우더도장', isActive: true },
];

const ITEM_TYPE_OPTIONS = [
  { value: 'FG', label: '제품 (FG)' },
  { value: 'PT', label: '부품 (PT)' },
  { value: 'SM', label: '부자재 (SM)' },
  { value: 'RM', label: '원자재 (RM)' },
  { value: 'CS', label: '소모품 (CS)' }
];

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

export function ItemMasterDataManagement() {
  const {
    itemPages,
    addItemPage,
    updateItemPage,
    deleteItemPage,
    addSectionToPage,
    updateSection,
    deleteSection,
    addFieldToSection,
    updateField,
    deleteField,
    reorderFields,
    itemMasterFields,
    addItemMasterField,
    updateItemMasterField,
    deleteItemMasterField
  } = useData();

  const [activeTab, setActiveTab] = useState('hierarchy');

  const [unitOptions, setUnitOptions] = useState<MasterOption[]>(() => {
    const saved = localStorage.getItem(UNIT_OPTIONS_KEY);
    return saved ? JSON.parse(saved) : INITIAL_UNIT_OPTIONS;
  });

  const [materialOptions, setMaterialOptions] = useState<MasterOption[]>(() => {
    const saved = localStorage.getItem(MATERIAL_OPTIONS_KEY);
    return saved ? JSON.parse(saved) : INITIAL_MATERIAL_OPTIONS;
  });

  const [surfaceTreatmentOptions, setSurfaceTreatmentOptions] = useState<MasterOption[]>(() => {
    const saved = localStorage.getItem(SURFACE_TREATMENT_OPTIONS_KEY);
    return saved ? JSON.parse(saved) : INITIAL_SURFACE_TREATMENT_OPTIONS;
  });

  const [isOptionDialogOpen, setIsOptionDialogOpen] = useState(false);
  const [editingOptionType, setEditingOptionType] = useState<'unit' | 'material' | 'surface' | null>(null);
  const [newOptionValue, setNewOptionValue] = useState('');
  const [newOptionLabel, setNewOptionLabel] = useState('');

  // 계층구조 상태
  const [selectedPageId, setSelectedPageId] = useState<string | null>(itemPages[0]?.id || null);
  const selectedPage = itemPages.find(p => p.id === selectedPageId) || null;
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({});
  const [editingSectionId, setEditingSectionId] = useState<string | null>(null);
  const [editingSectionTitle, setEditingSectionTitle] = useState('');
  
  const [editingPageId, setEditingPageId] = useState<string | null>(null);
  const [editingPageName, setEditingPageName] = useState('');
  
  const [isPageDialogOpen, setIsPageDialogOpen] = useState(false);
  const [newPageName, setNewPageName] = useState('');
  const [newPageItemType, setNewPageItemType] = useState<'FG' | 'PT' | 'SM' | 'RM' | 'CS'>('FG');
  
  const [isSectionDialogOpen, setIsSectionDialogOpen] = useState(false);
  const [newSectionTitle, setNewSectionTitle] = useState('');
  const [newSectionDescription, setNewSectionDescription] = useState('');
  
  const [isFieldDialogOpen, setIsFieldDialogOpen] = useState(false);
  const [selectedSectionForField, setSelectedSectionForField] = useState<string | null>(null);
  const [editingFieldId, setEditingFieldId] = useState<string | null>(null);
  const [useMasterField, setUseMasterField] = useState(false);
  const [selectedMasterFieldId, setSelectedMasterFieldId] = useState('');
  const [newFieldName, setNewFieldName] = useState('');
  const [newFieldKey, setNewFieldKey] = useState('');
  const [newFieldInputType, setNewFieldInputType] = useState<'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea'>('textbox');
  const [newFieldRequired, setNewFieldRequired] = useState(false);
  const [newFieldOptions, setNewFieldOptions] = useState('');
  const [newFieldDescription, setNewFieldDescription] = useState('');
  
  // 조건부 항목 상태
  const [newFieldConditionEnabled, setNewFieldConditionEnabled] = useState(false);
  const [newFieldConditionField, setNewFieldConditionField] = useState('');
  const [newFieldConditionValue, setNewFieldConditionValue] = useState('');

  // 마스터 항목 관리 상태
  const [isMasterFieldDialogOpen, setIsMasterFieldDialogOpen] = useState(false);
  const [editingMasterFieldId, setEditingMasterFieldId] = useState<string | null>(null);
  const [newMasterFieldName, setNewMasterFieldName] = useState('');
  const [newMasterFieldKey, setNewMasterFieldKey] = useState('');
  const [newMasterFieldInputType, setNewMasterFieldInputType] = useState<'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea'>('textbox');
  const [newMasterFieldRequired, setNewMasterFieldRequired] = useState(false);
  const [newMasterFieldCategory, setNewMasterFieldCategory] = useState('공통');
  const [newMasterFieldDescription, setNewMasterFieldDescription] = useState('');
  const [newMasterFieldOptions, setNewMasterFieldOptions] = useState('');
  
  // 항목 탭 내부 품목 분류 서브탭 상태
  const [itemsSubTab, setItemsSubTab] = useState<string>('공통');

  // 품목분류 상태
  const [itemClassifications, setItemClassifications] = useState<ItemClassification[]>(() => {
    const saved = localStorage.getItem(ITEM_CLASSIFICATIONS_KEY);
    return saved ? JSON.parse(saved) : [];
  });
  const [isClassificationDialogOpen, setIsClassificationDialogOpen] = useState(false);
  const [editingClassificationId, setEditingClassificationId] = useState<string | null>(null);
  const [newClassificationName, setNewClassificationName] = useState('');
  const [newClassificationDescription, setNewClassificationDescription] = useState('');
  const [selectedClassificationId, setSelectedClassificationId] = useState<string | null>(null);
  const [availableFields, setAvailableFields] = useState<string[]>([]);

  useEffect(() => {
    localStorage.setItem(UNIT_OPTIONS_KEY, JSON.stringify(unitOptions));
  }, [unitOptions]);

  useEffect(() => {
    localStorage.setItem(MATERIAL_OPTIONS_KEY, JSON.stringify(materialOptions));
  }, [materialOptions]);

  useEffect(() => {
    localStorage.setItem(SURFACE_TREATMENT_OPTIONS_KEY, JSON.stringify(surfaceTreatmentOptions));
  }, [surfaceTreatmentOptions]);

  const handleAddOption = () => {
    if (!editingOptionType || !newOptionValue.trim() || !newOptionLabel.trim()) 
      return toast.error('모든 항목을 입력해주세요');
    
    const newOption: MasterOption = {
      id: `${editingOptionType}-${Date.now()}`,
      value: newOptionValue,
      label: newOptionLabel,
      isActive: true
    };

    if (editingOptionType === 'unit') setUnitOptions([...unitOptions, newOption]);
    else if (editingOptionType === 'material') setMaterialOptions([...materialOptions, newOption]);
    else if (editingOptionType === 'surface') setSurfaceTreatmentOptions([...surfaceTreatmentOptions, newOption]);

    setNewOptionValue('');
    setNewOptionLabel('');
    setIsOptionDialogOpen(false);
    toast.success('추가되었습니다');
  };

  const handleDeleteOption = (type: 'unit' | 'material' | 'surface', id: string) => {
    if (type === 'unit') setUnitOptions(unitOptions.filter(o => o.id !== id));
    else if (type === 'material') setMaterialOptions(materialOptions.filter(o => o.id !== id));
    else if (type === 'surface') setSurfaceTreatmentOptions(surfaceTreatmentOptions.filter(o => o.id !== id));
    toast.success('삭제되었습니다');
  };

  // 계층구조 핸들러
  const handleAddPage = () => {
    if (!newPageName.trim()) return toast.error('섹션명을 입력해주세요');
    const newPage: ItemPage = {
      id: `PAGE-${Date.now()}`,
      pageName: newPageName,
      itemType: newPageItemType,
      sections: [],
      isActive: true,
      createdAt: new Date().toISOString().split('T')[0]
    };
    addItemPage(newPage);
    setSelectedPageId(newPage.id);
    setNewPageName('');
    setIsPageDialogOpen(false);
    toast.success('섹션이 추가되었습니다');
  };

  const handleAddSection = () => {
    if (!selectedPage || !newSectionTitle.trim()) return toast.error('하위섹션 제목을 입력해주세요');
    const newSection: ItemSection = {
      id: `SECTION-${Date.now()}`,
      title: newSectionTitle,
      description: newSectionDescription || undefined,
      fields: [],
      order: selectedPage.sections.length + 1,
      isCollapsible: true,
      isCollapsed: false,
      createdAt: new Date().toISOString().split('T')[0]
    };
    addSectionToPage(selectedPage.id, newSection);
    
    // 새로 추가된 하위섹션을 자동으로 확장
    setExpandedSections(prev => ({ ...prev, [newSection.id]: true }));
    
    setNewSectionTitle('');
    setNewSectionDescription('');
    setIsSectionDialogOpen(false);
    toast.success('하위섹션이 추가되었습니다');
  };

  const handleEditSectionTitle = (sectionId: string, currentTitle: string) => {
    setEditingSectionId(sectionId);
    setEditingSectionTitle(currentTitle);
  };

  const handleSaveSectionTitle = () => {
    if (!selectedPage || !editingSectionId) return;
    if (!editingSectionTitle.trim()) return toast.error('하위섹션 제목을 입력해주세요');
    
    updateSection(selectedPage.id, editingSectionId, { title: editingSectionTitle });
    setEditingSectionId(null);
    setEditingSectionTitle('');
    toast.success('하위섹션 제목이 수정되었습니다');
  };

  const handleEditField = (sectionId: string, field: ItemField) => {
    setSelectedSectionForField(sectionId);
    setEditingFieldId(field.id);
    setNewFieldName(field.name);
    setNewFieldKey(field.fieldKey);
    setNewFieldInputType(field.property.inputType);
    setNewFieldRequired(field.property.required);
    setNewFieldOptions(field.property.options?.join(',') || '');
    setNewFieldDescription(field.description || '');
    setNewFieldConditionEnabled(!!field.displayCondition);
    setNewFieldConditionField(field.displayCondition?.fieldKey || '');
    setNewFieldConditionValue(field.displayCondition?.expectedValue || '');
    setUseMasterField(!!field.masterFieldId);
    setSelectedMasterFieldId(field.masterFieldId || '');
    setIsFieldDialogOpen(true);
  };

  const handleAddField = () => {
    if (!selectedPage || !selectedSectionForField || !newFieldName.trim() || !newFieldKey.trim()) 
      return toast.error('모든 필수 항목을 입력해주세요');
    
    if (editingFieldId) {
      // 수정 모드
      updateField(selectedPage.id, selectedSectionForField, editingFieldId, {
        name: newFieldName,
        fieldKey: newFieldKey,
        property: {
          inputType: newFieldInputType,
          required: newFieldRequired,
          row: 1,
          col: 1,
          options: newFieldInputType === 'dropdown' && newFieldOptions.trim() 
            ? newFieldOptions.split(',').map(o => o.trim()) 
            : undefined
        },
        description: newFieldDescription || undefined,
        displayCondition: newFieldConditionEnabled ? {
          fieldKey: newFieldConditionField,
          expectedValue: newFieldConditionValue
        } : undefined,
        masterFieldId: selectedMasterFieldId || undefined
      });
      toast.success('항목이 수정되었습니다');
    } else {
      // 추가 모드
      const newField: ItemField = {
        id: `FIELD-${Date.now()}`,
        name: newFieldName,
        fieldKey: newFieldKey,
        property: {
          inputType: newFieldInputType,
          required: newFieldRequired,
          row: 1,
          col: 1,
          options: newFieldInputType === 'dropdown' && newFieldOptions.trim() 
            ? newFieldOptions.split(',').map(o => o.trim()) 
            : undefined
        },
        description: newFieldDescription || undefined,
        // 조건부 항목 설정
        displayCondition: newFieldConditionEnabled ? {
          fieldKey: newFieldConditionField,
          expectedValue: newFieldConditionValue
        } : undefined,
        masterFieldId: selectedMasterFieldId || undefined,
        createdAt: new Date().toISOString().split('T')[0]
      };
      
      addFieldToSection(selectedPage.id, selectedSectionForField, newField);
      toast.success('항목이 추가되었습니다');
    }
    
    // 폼 초기화
    setEditingFieldId(null);
    setUseMasterField(false);
    setSelectedMasterFieldId('');
    setNewFieldName('');
    setNewFieldKey('');
    setNewFieldInputType('textbox');
    setNewFieldRequired(false);
    setNewFieldOptions('');
    setNewFieldDescription('');
    setNewFieldConditionEnabled(false);
    setNewFieldConditionField('');
    setNewFieldConditionValue('');
    setIsFieldDialogOpen(false);
  };

  // 마스터 항목 선택 시 폼 자동 채우기
  const handleSelectMasterField = (masterFieldId: string) => {
    setSelectedMasterFieldId(masterFieldId);
    
    if (masterFieldId && masterFieldId !== '__NONE__') {
      const masterField = itemMasterFields.find(f => f.id === masterFieldId);
      if (masterField) {
        setNewFieldName(masterField.name);
        setNewFieldKey(masterField.fieldKey);
        setNewFieldInputType(masterField.property.inputType);
        setNewFieldRequired(masterField.property.required);
        setNewFieldOptions(masterField.property.options?.join(', ') || '');
        setNewFieldDescription(masterField.description || '');
      }
    } else {
      // 직접 입력 모드로 전환 시 폼 초기화
      setNewFieldName('');
      setNewFieldKey('');
      setNewFieldInputType('textbox');
      setNewFieldRequired(false);
      setNewFieldOptions('');
      setNewFieldDescription('');
    }
  };

  // 마스터 항목 관리 핸들러
  const handleAddMasterField = () => {
    if (!newMasterFieldName.trim() || !newMasterFieldKey.trim()) 
      return toast.error('항목명과 필드 키를 입력해주세요');

    const newMasterField: ItemMasterField = {
      id: `MASTER-${Date.now()}`,
      name: newMasterFieldName,
      fieldKey: newMasterFieldKey,
      property: {
        inputType: newMasterFieldInputType,
        required: newMasterFieldRequired,
        row: 1,
        col: 1,
        options: newMasterFieldInputType === 'dropdown' && newMasterFieldOptions.trim()
          ? newMasterFieldOptions.split(',').map(o => o.trim())
          : undefined
      },
      category: newMasterFieldCategory,
      description: newMasterFieldDescription || undefined,
      isActive: true,
      createdAt: new Date().toISOString().split('T')[0]
    };

    addItemMasterField(newMasterField);

    // 폼 초기화
    setNewMasterFieldName('');
    setNewMasterFieldKey('');
    setNewMasterFieldInputType('textbox');
    setNewMasterFieldRequired(false);
    setNewMasterFieldCategory('공통');
    setNewMasterFieldDescription('');
    setNewMasterFieldOptions('');
    setIsMasterFieldDialogOpen(false);

    toast.success('마스터 항목이 추가되었습니다');
  };

  const handleEditMasterField = (field: ItemMasterField) => {
    setEditingMasterFieldId(field.id);
    setNewMasterFieldName(field.name);
    setNewMasterFieldKey(field.fieldKey);
    setNewMasterFieldInputType(field.property.inputType);
    setNewMasterFieldRequired(field.property.required);
    setNewMasterFieldCategory(field.category || '공통');
    setNewMasterFieldDescription(field.description || '');
    setNewMasterFieldOptions(field.property.options?.join(', ') || '');
    setIsMasterFieldDialogOpen(true);
  };

  const handleUpdateMasterField = () => {
    if (!editingMasterFieldId || !newMasterFieldName.trim() || !newMasterFieldKey.trim()) 
      return toast.error('항목명과 필드 키를 입력해주세요');

    updateItemMasterField(editingMasterFieldId, {
      name: newMasterFieldName,
      fieldKey: newMasterFieldKey,
      property: {
        inputType: newMasterFieldInputType,
        required: newMasterFieldRequired,
        row: 1,
        col: 1,
        options: newMasterFieldInputType === 'dropdown' && newMasterFieldOptions.trim()
          ? newMasterFieldOptions.split(',').map(o => o.trim())
          : undefined
      },
      category: newMasterFieldCategory,
      description: newMasterFieldDescription || undefined
    });

    // 폼 초기화
    setEditingMasterFieldId(null);
    setNewMasterFieldName('');
    setNewMasterFieldKey('');
    setNewMasterFieldInputType('textbox');
    setNewMasterFieldRequired(false);
    setNewMasterFieldCategory('공통');
    setNewMasterFieldDescription('');
    setNewMasterFieldOptions('');
    setIsMasterFieldDialogOpen(false);

    toast.success('마스터 항목이 수정되었습니다');
  };

  const handleDeleteMasterField = (id: string) => {
    if (confirm('이 마스터 항목을 삭제하시겠습니까?')) {
      deleteItemMasterField(id);
      toast.success('마스터 항목이 삭제되었습니다');
    }
  };

  const toggleSection = (sectionId: string) => {
    setExpandedSections(prev => ({ ...prev, [sectionId]: !prev[sectionId] }));
  };

  // 현재 섹션의 모든 필드 가져오기 (조건부 필드 참조용)
  const getAllFieldsInSection = (sectionId: string) => {
    if (!selectedPage) return [];
    const section = selectedPage.sections.find(s => s.id === sectionId);
    return section?.fields || [];
  };

  // 필드 순서 변경 핸들러
  const moveField = (sectionId: string, dragIndex: number, hoverIndex: number) => {
    if (!selectedPage) return;
    
    const section = selectedPage.sections.find(s => s.id === sectionId);
    if (!section) return;

    const fields = [...section.fields];
    const [removed] = fields.splice(dragIndex, 1);
    fields.splice(hoverIndex, 0, removed);
    
    const fieldIds = fields.map(f => f.id);
    reorderFields(selectedPage.id, sectionId, fieldIds);
  };

  return (
      <PageLayout>
      <PageHeader
        title="품목기준관리"
        description="품목관리에서 사용되는 기준 정보를 설정하고 관리합니다"
        icon={Database}
      />

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-6">
          <TabsTrigger value="hierarchy">
            <Database className="w-4 h-4 mr-2" />
            계층구조
          </TabsTrigger>
          <TabsTrigger value="items">
            <ListTree className="w-4 h-4 mr-2" />
            항목
          </TabsTrigger>
          <TabsTrigger value="units">
            <ListTree className="w-4 h-4 mr-2" />
            단위
          </TabsTrigger>
          <TabsTrigger value="materials">
            <FileText className="w-4 h-4 mr-2" />
            재질
          </TabsTrigger>
          <TabsTrigger value="surface">
            <Settings className="w-4 h-4 mr-2" />
            표면처리
          </TabsTrigger>
          <TabsTrigger value="specifications">
            <Settings className="w-4 h-4 mr-2" />
            규격
          </TabsTrigger>
        </TabsList>

        {/* 단위 탭 */}
        <TabsContent value="units" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>단위 관리</CardTitle>
                <Button onClick={() => { setEditingOptionType('unit'); setIsOptionDialogOpen(true); }}>
                  <Plus className="w-4 h-4 mr-2" />추가
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <table className="w-full">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="h-10 px-4 text-left align-middle font-medium w-[50px]">번호</th>
                      <th className="h-10 px-4 text-left align-middle font-medium">값 (Value)</th>
                      <th className="h-10 px-4 text-left align-middle font-medium">라벨 (Label)</th>
                      <th className="h-10 px-4 text-left align-middle font-medium w-[100px]">작업</th>
                    </tr>
                  </thead>
                  <tbody>
                    {unitOptions.length === 0 ? (
                      <tr>
                        <td colSpan={4} className="h-24 px-4 text-center text-muted-foreground">
                          아직 수치를 등록이 없습니다
                        </td>
                      </tr>
                    ) : (
                      unitOptions.map((option, index) => (
                        <tr key={option.id} className="border-b">
                          <td className="p-4">{index + 1}</td>
                          <td className="p-4">{option.value}</td>
                          <td className="p-4">{option.label}</td>
                          <td className="p-4">
                            <Button variant="ghost" size="sm" onClick={() => handleDeleteOption('unit', option.id)}>
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 재질 탭 */}
        <TabsContent value="materials" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>재질 관리</CardTitle>
                <Button onClick={() => { setEditingOptionType('material'); setIsOptionDialogOpen(true); }}>
                  <Plus className="w-4 h-4 mr-2" />추가
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <table className="w-full">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="h-10 px-4 text-left align-middle font-medium w-[50px]">번호</th>
                      <th className="h-10 px-4 text-left align-middle font-medium">값 (Value)</th>
                      <th className="h-10 px-4 text-left align-middle font-medium">라벨 (Label)</th>
                      <th className="h-10 px-4 text-left align-middle font-medium w-[100px]">작업</th>
                    </tr>
                  </thead>
                  <tbody>
                    {materialOptions.length === 0 ? (
                      <tr>
                        <td colSpan={4} className="h-24 px-4 text-center text-muted-foreground">
                          아직 수치를 등록이 없습니다
                        </td>
                      </tr>
                    ) : (
                      materialOptions.map((option, index) => (
                        <tr key={option.id} className="border-b">
                          <td className="p-4">{index + 1}</td>
                          <td className="p-4">{option.value}</td>
                          <td className="p-4">{option.label}</td>
                          <td className="p-4">
                            <Button variant="ghost" size="sm" onClick={() => handleDeleteOption('material', option.id)}>
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 표면처리 탭 */}
        <TabsContent value="surface" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>표면처리 관리</CardTitle>
                <Button onClick={() => { setEditingOptionType('surface'); setIsOptionDialogOpen(true); }}>
                  <Plus className="w-4 h-4 mr-2" />추가
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <table className="w-full">
                  <thead>
                    <tr className="border-b bg-muted/50">
                      <th className="h-10 px-4 text-left align-middle font-medium w-[50px]">번호</th>
                      <th className="h-10 px-4 text-left align-middle font-medium">값 (Value)</th>
                      <th className="h-10 px-4 text-left align-middle font-medium">라벨 (Label)</th>
                      <th className="h-10 px-4 text-left align-middle font-medium w-[100px]">작업</th>
                    </tr>
                  </thead>
                  <tbody>
                    {surfaceTreatmentOptions.length === 0 ? (
                      <tr>
                        <td colSpan={4} className="h-24 px-4 text-center text-muted-foreground">
                          아직 수치를 등록이 없습니다
                        </td>
                      </tr>
                    ) : (
                      surfaceTreatmentOptions.map((option, index) => (
                        <tr key={option.id} className="border-b">
                          <td className="p-4">{index + 1}</td>
                          <td className="p-4">{option.value}</td>
                          <td className="p-4">{option.label}</td>
                          <td className="p-4">
                            <Button variant="ghost" size="sm" onClick={() => handleDeleteOption('surface', option.id)}>
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 규격 탭 */}
        <TabsContent value="specifications" className="space-y-4">
          <SpecificationManagement />
        </TabsContent>

        {/* 항목 탭 */}
        <TabsContent value="items" className="space-y-4">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>마스터 항목 관리</CardTitle>
                  <CardDescription>재사용 가능한 항목 템플릿을 품목 분류별로 관리합니다</CardDescription>
                </div>
                <Button onClick={() => setIsMasterFieldDialogOpen(true)}>
                  <Plus className="h-4 w-4 mr-2" />항목 추가
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {/* 품목 분류별 서브 탭 */}
              <Tabs value={itemsSubTab} onValueChange={(v: any) => setItemsSubTab(v)}>
                <div className="space-y-2 mb-4">
                  <TabsList className="grid w-full grid-cols-5">
                    <TabsTrigger value="공통">공통</TabsTrigger>
                    <TabsTrigger value="제품">제품</TabsTrigger>
                    <TabsTrigger value="부품">부품</TabsTrigger>
                    <TabsTrigger value="부자재">부자재</TabsTrigger>
                    <TabsTrigger value="원자재">원자재</TabsTrigger>
                  </TabsList>
                  <TabsList className="grid w-full grid-cols-5">
                    <TabsTrigger value="부품-조립">부품-조립</TabsTrigger>
                    <TabsTrigger value="부품-절곡">부품-절곡</TabsTrigger>
                    <TabsTrigger value="부품-구매">부품-구매</TabsTrigger>
                    <TabsTrigger value="소모품">소모품</TabsTrigger>
                    <TabsTrigger value="인정정보">인정정보</TabsTrigger>
                  </TabsList>
                </div>

                {['공통', '제품', '부품', '부품-조립', '부품-절곡', '부품-구매', '부자재', '원자재', '소모품', '인정정보'].map((categoryName) => {
                  const filteredFields = itemMasterFields.filter(f => f.category === categoryName);

                  return (
                    <TabsContent key={categoryName} value={categoryName} className="mt-0">
                      {filteredFields.length === 0 ? (
                        <div className="text-center py-8">
                          <p className="text-muted-foreground mb-2">등록된 {categoryName} 항목이 없습니다</p>
                          <p className="text-sm text-muted-foreground">
                            항목 추가 버튼을 눌러 재사용 가능한 항목을 등록하세요.
                          </p>
                        </div>
                      ) : (
                        <div className="space-y-2">
                          {filteredFields.map((field) => (
                            <div key={field.id} className="flex items-center justify-between p-4 border rounded hover:bg-gray-50 transition-colors">
                              <div className="flex-1">
                                <div className="flex items-center gap-2">
                                  <span className="font-medium">{field.name}</span>
                                  <Badge variant="outline" className="text-xs">
                                    {INPUT_TYPE_OPTIONS.find(t => t.value === field.property.inputType)?.label}
                                  </Badge>
                                  {field.property.required && (
                                    <Badge variant="destructive" className="text-xs">필수</Badge>
                                  )}
                                  <Badge variant="secondary" className="text-xs">{field.category}</Badge>
                                </div>
                                <div className="text-sm text-muted-foreground mt-1">
                                  필드키: {field.fieldKey}
                                  {field.description && (
                                    <span className="ml-2">• {field.description}</span>
                                  )}
                                </div>
                                {field.property.options && field.property.options.length > 0 && (
                                  <div className="text-xs text-gray-500 mt-1">
                                    옵션: {field.property.options.join(', ')}
                                  </div>
                                )}
                              </div>
                              <div className="flex gap-2">
                                <Button 
                                  size="sm" 
                                  variant="ghost" 
                                  onClick={() => handleEditMasterField(field)}
                                >
                                  <Edit className="h-4 w-4 text-blue-500" />
                                </Button>
                                <Button 
                                  size="sm" 
                                  variant="ghost" 
                                  onClick={() => handleDeleteMasterField(field.id)}
                                >
                                  <Trash2 className="h-4 w-4 text-red-500" />
                                </Button>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </TabsContent>
                  );
                })}
              </Tabs>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 계층구조 탭 */}
        <TabsContent value="hierarchy" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
            {/* 섹션 목록 */}
            <Card className="lg:col-span-1">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="text-base">섹션</CardTitle>
                  <Button size="sm" onClick={() => setIsPageDialogOpen(true)}>
                    <Plus className="h-4 w-4" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="space-y-2">
                {itemPages.length === 0 ? (
                  <p className="text-sm text-gray-500 text-center py-4">섹션을 추가해주세요</p>
                ) : (
                  itemPages.map(page => (
                    <div key={page.id} className="relative group">
                      {editingPageId === page.id ? (
                        <div className="flex items-center gap-1 p-2 border rounded bg-white">
                          <Input
                            value={editingPageName}
                            onChange={(e) => setEditingPageName(e.target.value)}
                            className="h-7 text-sm"
                            autoFocus
                            onKeyDown={(e) => {
                              if (e.key === 'Enter') {
                                if (!editingPageName.trim()) return toast.error('섹션명을 입력해주세요');
                                updateItemPage(page.id, { pageName: editingPageName });
                                setEditingPageId(null);
                                toast.success('섹션명이 수정되었습니다');
                              }
                              if (e.key === 'Escape') setEditingPageId(null);
                            }}
                          />
                        </div>
                      ) : (
                        <div
                          onClick={() => setSelectedPageId(page.id)}
                          onDoubleClick={() => {
                            setEditingPageId(page.id);
                            setEditingPageName(page.pageName);
                          }}
                          className={`w-full text-left p-2 rounded hover:bg-gray-50 transition-colors cursor-pointer ${
                            selectedPage?.id === page.id ? 'bg-blue-50 border border-blue-200' : 'border'
                          }`}
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex-1">
                              <div className="text-sm">{page.pageName}</div>
                              <div className="text-xs text-gray-500">
                                {ITEM_TYPE_OPTIONS.find(t => t.value === page.itemType)?.label}
                              </div>
                            </div>
                            <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                              <Button
                                size="sm"
                                variant="ghost"
                                className="h-6 w-6 p-0"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  setEditingPageId(page.id);
                                  setEditingPageName(page.pageName);
                                }}
                              >
                                <Edit className="h-3 w-3" />
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                className="h-6 w-6 p-0"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  if (confirm('이 섹션과 모든 하위섹션, 항목을 삭제하시겠습니까?')) {
                                    deleteItemPage(page.id);
                                    if (selectedPageId === page.id) {
                                      setSelectedPageId(itemPages[0]?.id || null);
                                    }
                                    toast.success('섹션이 삭제되었습니다');
                                  }
                                }}
                              >
                                <Trash2 className="h-3 w-3 text-red-500" />
                              </Button>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  ))
                )}
              </CardContent>
            </Card>

            {/* 계층구조 */}
            <Card className="lg:col-span-3">
              <CardHeader>
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                  <CardTitle className="text-sm sm:text-base">{selectedPage?.pageName || '섹션을 선택하세요'}</CardTitle>
                  {selectedPage && (
                    <Button size="sm" onClick={() => setIsSectionDialogOpen(true)} className="w-full sm:w-auto">
                      <Plus className="h-4 w-4 mr-2" />섹션 추가
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent>
                {selectedPage ? (
                  <div className="space-y-6">
                    {selectedPage.sections.length === 0 ? (
                      <p className="text-center text-gray-500 py-8">섹션을 추가해주세요</p>
                    ) : (
                      selectedPage.sections.map((section) => (
                        <div key={section.id} className="border rounded-lg overflow-hidden">
                          {/* 섹션 헤더 */}
                          <div className="bg-blue-50 border-b p-3">
                            <div className="flex items-center justify-between gap-2">
                              <div className="flex items-center gap-2 flex-1 min-w-0">
                                <FileText className="h-4 w-4 text-blue-600" />
                                {editingSectionId === section.id ? (
                                  <div className="flex items-center gap-2 flex-1">
                                    <Input
                                      value={editingSectionTitle}
                                      onChange={(e) => setEditingSectionTitle(e.target.value)}
                                      className="h-8 bg-white"
                                      autoFocus
                                      onKeyDown={(e) => {
                                        if (e.key === 'Enter') handleSaveSectionTitle();
                                        if (e.key === 'Escape') setEditingSectionId(null);
                                      }}
                                    />
                                    <Button size="sm" onClick={handleSaveSectionTitle}>
                                      <Check className="h-4 w-4" />
                                    </Button>
                                    <Button size="sm" variant="ghost" onClick={() => setEditingSectionId(null)}>
                                      <X className="h-4 w-4" />
                                    </Button>
                                  </div>
                                ) : (
                                  <div 
                                    className="flex items-center gap-2 flex-1 cursor-pointer group min-w-0"
                                    onClick={() => handleEditSectionTitle(section.id, section.title)}
                                  >
                                    <span className="font-medium text-blue-900 truncate text-sm sm:text-base">{section.title}</span>
                                    <Edit className="h-3 w-3 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
                                  </div>
                                )}
                              </div>
                              <Button 
                                size="sm" 
                                variant="ghost" 
                                className="flex-shrink-0"
                                onClick={() => {
                                  if (confirm('이 섹션과 모든 항목을 삭제하시겠습니까?')) {
                                    deleteSection(selectedPage.id, section.id);
                                    toast.success('섹션이 삭제되었습니다');
                                  }
                                }}
                              >
                                <Trash2 className="h-4 w-4 text-red-500" />
                              </Button>
                            </div>
                          </div>
                          
                          {/* 섹션 컨텐츠 (항목 목록) */}
                          <div className="p-4 bg-white space-y-2">
                            {section.fields.length === 0 ? (
                              <p className="text-sm text-gray-500 text-center py-4">항목을 추가해주세요</p>
                            ) : (
                              section.fields
                                .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
                                .map((field, index) => (
                                  <DraggableField
                                    key={field.id}
                                    field={field}
                                    index={index}
                                    moveField={(dragIndex, hoverIndex) => moveField(section.id, dragIndex, hoverIndex)}
                                    onDelete={() => {
                                      if (confirm('이 항목을 삭제하시겠습니까?')) {
                                        deleteField(selectedPage.id, section.id, field.id);
                                        toast.success('항목이 삭제되었습니다');
                                      }
                                    }}
                                    onEdit={() => handleEditField(section.id, field)}
                                  />
                                ))
                            )}
                            <Button 
                              size="sm" 
                              variant="outline" 
                              className="w-full mt-3"
                              onClick={() => {
                                setSelectedSectionForField(section.id);
                                setIsFieldDialogOpen(true);
                              }}
                            >
                              <Plus className="h-3 w-3 mr-1" />항목 추가
                            </Button>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                ) : (
                  <p className="text-center text-gray-500 py-8">왼쪽에서 섹션을 선택하세요</p>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* 옵션 추가 다이얼로그 */}
      <Dialog open={isOptionDialogOpen} onOpenChange={setIsOptionDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>옵션 추가</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>값 (코드)</Label>
              <Input value={newOptionValue} onChange={(e) => setNewOptionValue(e.target.value)} />
            </div>
            <div>
              <Label>라벨 (표시명)</Label>
              <Input value={newOptionLabel} onChange={(e) => setNewOptionLabel(e.target.value)} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsOptionDialogOpen(false)}>취소</Button>
            <Button onClick={handleAddOption}>추가</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 섹션 추가 다이얼로그 */}
      <Dialog open={isPageDialogOpen} onOpenChange={setIsPageDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>섹션 추가</DialogTitle>
            <DialogDescription>새로운 품목 섹션을 생성합니다</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>섹션명 *</Label>
              <Input 
                value={newPageName} 
                onChange={(e) => setNewPageName(e.target.value)} 
                placeholder="예: 품목 등록"
              />
            </div>
            <div>
              <Label>품목유형 *</Label>
              <Select value={newPageItemType} onValueChange={(v: any) => setNewPageItemType(v)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {ITEM_TYPE_OPTIONS.map(opt => (
                    <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsPageDialogOpen(false)}>취소</Button>
            <Button onClick={handleAddPage}>추가</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 섹션 추가 다이얼로그 */}
      <Dialog open={isSectionDialogOpen} onOpenChange={setIsSectionDialogOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>섹션 추가</DialogTitle>
            <DialogDescription>새로운 섹션을 추가합니다</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>섹션 제목 *</Label>
              <Input 
                value={newSectionTitle} 
                onChange={(e) => setNewSectionTitle(e.target.value)} 
                placeholder="예: 기본정보, BOM"
              />
            </div>
            <div>
              <Label>설명 (선택)</Label>
              <Textarea 
                value={newSectionDescription} 
                onChange={(e) => setNewSectionDescription(e.target.value)} 
                placeholder="섹션에 대한 설명"
              />
            </div>
          </div>
          <DialogFooter className="flex-col sm:flex-row gap-2">
            <Button variant="outline" onClick={() => setIsSectionDialogOpen(false)} className="w-full sm:w-auto">취소</Button>
            <Button onClick={handleAddSection} className="w-full sm:w-auto">추가</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 항목 추가 다이얼로그 */}
      <Dialog open={isFieldDialogOpen} onOpenChange={(open) => {
        setIsFieldDialogOpen(open);
        if (!open) {
          setEditingFieldId(null);
          setUseMasterField(false);
          setSelectedMasterFieldId('');
          setNewFieldName('');
          setNewFieldKey('');
          setNewFieldInputType('textbox');
          setNewFieldRequired(false);
          setNewFieldOptions('');
          setNewFieldConditionEnabled(false);
          setNewFieldConditionField('');
          setNewFieldConditionValue('');
          setNewFieldDescription('');
        }
      }}>
        <DialogContent className="max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingFieldId ? '항목 수정' : '항목 추가'}</DialogTitle>
            <DialogDescription>{editingFieldId ? '항목과 속성을 수정합니다' : '새로운 항목과 속성을 추가합니다'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {/* 마스터 항목 선택 */}
            <div className="bg-blue-50 p-4 rounded-lg">
              <div className="flex items-center gap-2 mb-3">
                <Switch checked={useMasterField} onCheckedChange={(checked) => {
                  setUseMasterField(checked);
                  if (!checked) {
                    setSelectedMasterFieldId('');
                    setNewFieldName('');
                    setNewFieldKey('');
                    setNewFieldInputType('textbox');
                    setNewFieldRequired(false);
                    setNewFieldOptions('');
                  }
                }} />
                <Label>마스터 항목에서 불러오기</Label>
              </div>
              
              {useMasterField && (
                <div>
                  <Label>마스터 항목 선택</Label>
                  <Select value={selectedMasterFieldId} onValueChange={handleSelectMasterField}>
                    <SelectTrigger>
                      <SelectValue placeholder="항목 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="__NONE__">직접 입력</SelectItem>
                      {itemMasterFields.map(field => (
                        <SelectItem key={field.id} value={field.id}>
                          {field.name} ({field.category})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-blue-600 mt-2">
                    마스터 항목을 선택하면 자동으로 항목 정보가 채워집니다.
                  </p>
                </div>
              )}
            </div>

            <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="예: 품목코드"
                  disabled={useMasterField && !!selectedMasterFieldId}
                />
              </div>
              <div>
                <Label>필드 키 *</Label>
                <Input 
                  value={newFieldKey} 
                  onChange={(e) => setNewFieldKey(e.target.value)} 
                  placeholder="예: itemCode (영문)"
                  disabled={useMasterField && !!selectedMasterFieldId}
                />
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>입력방식</Label>
                <Select 
                  value={newFieldInputType} 
                  onValueChange={(v: any) => setNewFieldInputType(v)}
                  disabled={useMasterField && !!selectedMasterFieldId}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {INPUT_TYPE_OPTIONS.map(opt => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center gap-2 pt-8">
                <Switch 
                  checked={newFieldRequired} 
                  onCheckedChange={setNewFieldRequired}
                  disabled={useMasterField && !!selectedMasterFieldId}
                />
                <Label>필수 항목</Label>
              </div>
            </div>

            {newFieldInputType === 'dropdown' && (
              <div>
                <Label>드롭다운 옵션</Label>
                <Input 
                  value={newFieldOptions} 
                  onChange={(e) => setNewFieldOptions(e.target.value)} 
                  placeholder="제품,부품,원자재 (쉼표로 구분)"
                  disabled={useMasterField && !!selectedMasterFieldId}
                />
                <p className="text-xs text-gray-500 mt-1">쉼표(,)로 구분하여 입력하세요</p>
              </div>
            )}

            <div className="border-t pt-4">
              <div className="flex items-center gap-2 mb-3">
                <Switch 
                  checked={newFieldConditionEnabled} 
                  onCheckedChange={setNewFieldConditionEnabled} 
                />
                <Label>조건부 항목 (특정 값일 때만 표시)</Label>
              </div>
              
              {newFieldConditionEnabled && (
                <div className="ml-6 space-y-3 bg-blue-50 p-3 rounded">
                  <div>
                    <Label>조건 필드</Label>
                    <Select value={newFieldConditionField} onValueChange={setNewFieldConditionField}>
                      <SelectTrigger>
                        <SelectValue placeholder="다른 항목 선택" />
                      </SelectTrigger>
                      <SelectContent>
                        {selectedSectionForField && getAllFieldsInSection(selectedSectionForField).map(field => (
                          <SelectItem key={field.fieldKey} value={field.fieldKey}>
                            {field.name} ({field.fieldKey})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-gray-600 mt-1">
                      어떤 항목의 값에 따라 표시할지 선택
                    </p>
                  </div>
                  <div>
                    <Label>조건 값</Label>
                    <Input 
                      value={newFieldConditionValue} 
                      onChange={(e) => setNewFieldConditionValue(e.target.value)} 
                      placeholder="예: 제품"
                    />
                    <p className="text-xs text-gray-600 mt-1">
                      선택한 항목이 이 값일 때 현재 항목 표시
                    </p>
                  </div>
                </div>
              )}
            </div>

            <div>
              <Label>설명</Label>
              <Textarea 
                value={newFieldDescription} 
                onChange={(e) => setNewFieldDescription(e.target.value)} 
                placeholder="항목에 대한 설명"
              />
              <p className="text-xs text-gray-500 mt-1">* 제품 유형에 따라 품목 분류를 표시 [필수]</p>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsFieldDialogOpen(false)}>취소</Button>
            <Button onClick={handleAddField}>저장</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 마스터 항목 추가/편집 다이얼로그 */}
      <Dialog open={isMasterFieldDialogOpen} onOpenChange={(open) => {
        setIsMasterFieldDialogOpen(open);
        if (!open) {
          setEditingMasterFieldId(null);
          setNewMasterFieldName('');
          setNewMasterFieldKey('');
          setNewMasterFieldInputType('textbox');
          setNewMasterFieldRequired(false);
          setNewMasterFieldCategory('공통');
          setNewMasterFieldDescription('');
          setNewMasterFieldOptions('');
        }
      }}>
        <DialogContent className="max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingMasterFieldId ? '마스터 항목 편집' : '마스터 항목 추가'}</DialogTitle>
            <DialogDescription>{editingMasterFieldId ? '항목과 속성을 수정합니다' : '새로운 항목과 속성을 추가합니다'}</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label>항목명 *</Label>
                <Input 
                  value={newMasterFieldName} 
                  onChange={(e) => setNewMasterFieldName(e.target.value)} 
                  placeholder="예: 품목코드"
                />
              </div>
              <div>
                <Label>필드 키 *</Label>
                <Input 
                  value={newMasterFieldKey} 
                  onChange={(e) => setNewMasterFieldKey(e.target.value)} 
                  placeholder="예: itemCode (영문)"
                />
              </div>
            </div>
            
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label>입력방식</Label>
                <Select value={newMasterFieldInputType} onValueChange={(v: any) => setNewMasterFieldInputType(v)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {INPUT_TYPE_OPTIONS.map(opt => (
                      <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center gap-2 sm:pt-8">
                <Switch checked={newMasterFieldRequired} onCheckedChange={setNewMasterFieldRequired} />
                <Label>필수 항목</Label>
              </div>
            </div>

            <div>
              <Label>카테고리</Label>
              <Input 
                value={newMasterFieldCategory} 
                onChange={(e) => setNewMasterFieldCategory(e.target.value)} 
                placeholder="예: 공통, 제품, 부품"
              />
            </div>

            <div>
              <Label>설명</Label>
              <Textarea 
                value={newMasterFieldDescription} 
                onChange={(e) => setNewMasterFieldDescription(e.target.value)} 
                placeholder="항목에 대한 설명"
              />
              <p className="text-xs text-gray-500 mt-1">* 제품 유형에 따라 품목 분류를 표시 [필수]</p>
            </div>

            {newMasterFieldInputType === 'dropdown' && (
              <div>
                <Label>드롭다운 옵션</Label>
                <Input 
                  value={newMasterFieldOptions} 
                  onChange={(e) => setNewMasterFieldOptions(e.target.value)} 
                  placeholder="제품,부품,원자재 (쉼표로 구분)"
                />
                <p className="text-xs text-gray-500 mt-1">쉼표(,)로 구분하여 입력하세요</p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsMasterFieldDialogOpen(false)}>취소</Button>
            <Button onClick={editingMasterFieldId ? handleUpdateMasterField : handleAddMasterField}>
              {editingMasterFieldId ? '수정' : '추가'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}