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 } from './contexts/DataContext';
import { 
  Database, 
  Plus, 
  Trash2, 
  ChevronRight, 
  ChevronDown,
  FolderTree,
  Folder,
  FileText,
  Settings,
  ListTree,
  Save,
  X,
  GripVertical,
  Eye,
  EyeOff
} from 'lucide-react';
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';

// 품목분류 로컬스토리지 키
const ITEM_CATEGORIES_KEY = 'item-categories';
const UNIT_OPTIONS_KEY = 'unit-options';
const MATERIAL_OPTIONS_KEY = 'material-options';
const SURFACE_TREATMENT_OPTIONS_KEY = 'surface-treatment-options';

// 품목분류 타입
interface ItemCategoryStructure {
  [category1: string]: {
    [category2: string]: string[];
  };
}

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

// 초기 데이터
const INITIAL_ITEM_CATEGORIES: ItemCategoryStructure = {
  "본체부품": {
    "가이드시스템": ["가이드레일"],
    "케이스시스템": ["케이스 전면부", "케이스 접검구"],
  },
};

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: '텍스트영역' },
  { value: 'section', label: '섹션 참조 (풀세트)' }
];

// 드래그 가능한 섹션 컴포넌트 (네이티브 HTML5 드래그 앤 드롭)
interface DraggableSectionProps {
  section: ItemSection;
  index: number;
  pageId: string;
  isExpanded: boolean;
  onToggle: () => void;
  onDelete: () => void;
  onMoveSection: (dragIndex: number, hoverIndex: number) => void;
  children: React.ReactNode;
}

function DraggableSection({ section, index, pageId, isExpanded, onToggle, onDelete, onMoveSection, children }: DraggableSectionProps) {
  const [isDragging, setIsDragging] = useState(false);

  const handleDragStart = (e: React.DragEvent) => {
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', JSON.stringify({ type: 'section', index, id: section.id }));
    setIsDragging(true);
  };

  const handleDragEnd = () => {
    setIsDragging(false);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    try {
      const data = JSON.parse(e.dataTransfer.getData('text/plain'));
      if (data.type === 'section' && data.index !== index) {
        onMoveSection(data.index, index);
      }
    } catch (err) {
      // Ignore
    }
  };

  return (
    <div 
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      className={`border rounded-lg p-3 transition-opacity ${isDragging ? 'opacity-50' : 'opacity-100'}`}
    >
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-2">
          <div className="cursor-move">
            <GripVertical className="h-4 w-4 text-gray-400" />
          </div>
          <button onClick={onToggle}>
            {isExpanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
          </button>
          <FileText className="h-4 w-4" />
          <span>{section.title}</span>
        </div>
        <Button size="sm" variant="ghost" onClick={onDelete}>
          <Trash2 className="h-4 w-4" />
        </Button>
      </div>
      {isExpanded && children}
    </div>
  );
}

// 드래그 가능한 필드 컴포넌트 (네이티브 HTML5 드래그 앤 드롭)
interface DraggableFieldProps {
  field: ItemField;
  index: number;
  pageId: string;
  sectionId: string;
  onDelete: () => void;
  onMoveField: (dragIndex: number, hoverIndex: number) => void;
  allPages: ItemPage[];
}

function DraggableField({ field, index, pageId, sectionId, onDelete, onMoveField, allPages }: DraggableFieldProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [isDragging, setIsDragging] = useState(false);

  const handleDragStart = (e: React.DragEvent) => {
    e.stopPropagation();
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', JSON.stringify({ type: 'field', index, sectionId, id: field.id }));
    setIsDragging(true);
  };

  const handleDragEnd = () => {
    setIsDragging(false);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    try {
      const data = JSON.parse(e.dataTransfer.getData('text/plain'));
      if (data.type === 'field' && data.sectionId === sectionId && data.index !== index) {
        onMoveField(data.index, index);
      }
    } catch (err) {
      // Ignore
    }
  };

  const isSectionReference = field.property.inputType === 'section';

  // 참조된 섹션 찾기
  const getReferencedSection = (): { page: ItemPage; section: ItemSection } | null => {
    if (!isSectionReference || !field.referenceSectionId || !field.referencePageId) return null;
    const page = allPages.find(p => p.id === field.referencePageId);
    if (!page) return null;
    const section = page.sections.find(s => s.id === field.referenceSectionId);
    if (!section) return null;
    return { page, section };
  };

  const referencedData = getReferencedSection();

  return (
    <div 
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      className={`rounded transition-opacity ${
        isSectionReference ? 'bg-blue-50 border border-blue-200' : 'bg-gray-50'
      } ${isDragging ? 'opacity-50' : 'opacity-100'}`}
    >
      <div className="flex items-center justify-between p-2">
        <div className="flex items-center gap-2 flex-1">
          <div className="cursor-move">
            <GripVertical className="h-3 w-3 text-gray-400" />
          </div>
          {isSectionReference && (
            <button onClick={() => setIsExpanded(!isExpanded)} className="flex items-center gap-1">
              {isExpanded ? <ChevronDown className="h-3 w-3 text-blue-600" /> : <ChevronRight className="h-3 w-3 text-blue-600" />}
            </button>
          )}
          {isSectionReference && (
            <FolderTree className="h-3 w-3 text-blue-600" />
          )}
          <span className="text-sm">{field.name}</span>
          {isSectionReference && (
            <>
              <Badge variant="secondary" className="text-xs">섹션 참조</Badge>
              {referencedData && (
                <span className="text-xs text-gray-500">
                  → {referencedData.section.title} ({referencedData.section.fields.length}개 필드)
                </span>
              )}
            </>
          )}
        </div>
        <Button size="sm" variant="ghost" onClick={onDelete}>
          <X className="h-3 w-3" />
        </Button>
      </div>
      
      {/* 섹션 참조일 때 확장된 필드 목록 */}
      {isSectionReference && isExpanded && referencedData && (
        <div className="ml-8 mr-2 mb-2 space-y-1 border-l-2 border-blue-300 pl-3">
          <p className="text-xs text-blue-700 mb-1">참조된 필드:</p>
          {referencedData.section.fields.map((refField) => (
            <div key={refField.id} className="flex items-center gap-2 p-1.5 bg-white rounded text-xs">
              <Badge variant="outline" className="text-xs">{refField.property.inputType}</Badge>
              <span>{refField.name}</span>
              <span className="text-gray-400">({refField.fieldKey})</span>
              {refField.property.required && (
                <Badge variant="destructive" className="text-xs">필수</Badge>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

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

  const [activeTab, setActiveTab] = useState('categories');
  
  // 품목분류 상태
  const [itemCategories, setItemCategories] = useState<ItemCategoryStructure>(() => {
    const saved = localStorage.getItem(ITEM_CATEGORIES_KEY);
    return saved ? JSON.parse(saved) : INITIAL_ITEM_CATEGORIES;
  });

  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 [newCategory1, setNewCategory1] = useState('');
  const [newCategory2, setNewCategory2] = useState('');
  const [newCategory3, setNewCategory3] = useState('');
  const [selectedCategory1, setSelectedCategory1] = useState('');
  const [selectedCategory2, setSelectedCategory2] = useState('');

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

  // 계층구조 상태
  const [selectedPage, setSelectedPage] = useState<ItemPage | null>(itemPages[0] || null);
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({});
  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 [newFieldName, setNewFieldName] = useState('');
  const [newFieldKey, setNewFieldKey] = useState('');
  const [newFieldInputType, setNewFieldInputType] = useState<'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea' | 'section'>('textbox');
  const [newFieldRequired, setNewFieldRequired] = useState(false);
  const [selectedReferenceSectionPageId, setSelectedReferenceSectionPageId] = useState('');
  const [selectedReferenceSectionId, setSelectedReferenceSectionId] = useState('');

  // 섹션 참조를 위한 모든 섹션 목록 가져오기
  const getAllAvailableSections = () => {
    const sections: { pageId: string; pageName: string; section: ItemSection }[] = [];
    itemPages.forEach(page => {
      page.sections.forEach(section => {
        sections.push({ pageId: page.id, pageName: page.pageName, section });
      });
    });
    return sections;
  };

  // itemPages가 변경되면 selectedPage 업데이트
  useEffect(() => {
    if (selectedPage) {
      const updatedPage = itemPages.find(p => p.id === selectedPage.id);
      if (updatedPage) {
        setSelectedPage(updatedPage);
      }
    } else if (itemPages.length > 0) {
      setSelectedPage(itemPages[0]);
    }
  }, [itemPages]);

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

  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 handleAddCategory1 = () => {
    if (!newCategory1.trim()) return toast.error('대분류명을 입력해주세요');
    if (itemCategories[newCategory1]) return toast.error('이미 존재하는 대분류입니다');
    setItemCategories({ ...itemCategories, [newCategory1]: {} });
    setNewCategory1('');
    toast.success('대분류가 추가되었습니다');
  };

  const handleAddCategory2 = () => {
    if (!selectedCategory1) return toast.error('대분류를 선택해주세요');
    if (!newCategory2.trim()) return toast.error('중분류명을 입력해주세요');
    setItemCategories({
      ...itemCategories,
      [selectedCategory1]: { ...itemCategories[selectedCategory1], [newCategory2]: [] }
    });
    setNewCategory2('');
    toast.success('중분류가 추가되었습니다');
  };

  const handleAddCategory3 = () => {
    if (!selectedCategory1 || !selectedCategory2 || !newCategory3.trim()) 
      return toast.error('모든 항목을 입력해주세요');
    setItemCategories({
      ...itemCategories,
      [selectedCategory1]: {
        ...itemCategories[selectedCategory1],
        [selectedCategory2]: [...itemCategories[selectedCategory1][selectedCategory2], newCategory3]
      }
    });
    setNewCategory3('');
    toast.success('소분류가 추가되었습니다');
  };

  const handleDeleteCategory1 = (cat1: string) => {
    const newCategories = { ...itemCategories };
    delete newCategories[cat1];
    setItemCategories(newCategories);
    toast.success('삭제되었습니다');
  };

  const handleDeleteCategory2 = (cat1: string, cat2: string) => {
    const newCategories = { ...itemCategories };
    delete newCategories[cat1][cat2];
    setItemCategories(newCategories);
    toast.success('삭제되었습니다');
  };

  const handleDeleteCategory3 = (cat1: string, cat2: string, cat3: string) => {
    const newCategories = { ...itemCategories };
    newCategories[cat1][cat2] = newCategories[cat1][cat2].filter(c => c !== cat3);
    setItemCategories(newCategories);
    toast.success('삭제되었습니다');
  };

  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);
    setSelectedPage(newPage);
    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);
    setNewSectionTitle('');
    setNewSectionDescription('');
    setIsSectionDialogOpen(false);
    toast.success('섹션이 추가되었습니다');
  };

  const handleAddField = () => {
    if (!selectedPage || !selectedSectionForField || !newFieldName.trim() || !newFieldKey.trim()) 
      return toast.error('모든 필수 항목을 입력해주세요');
    
    // 섹션 참조 타입일 경우 참조 섹션 선택 확인
    if (newFieldInputType === 'section' && !selectedReferenceSectionId) {
      return toast.error('참조할 섹션을 선택해주세요');
    }
    
    const newField: ItemField = {
      id: `FIELD-${Date.now()}`,
      name: newFieldName,
      fieldKey: newFieldKey,
      property: {
        inputType: newFieldInputType,
        required: newFieldRequired,
        row: 1,
        col: 1
      },
      ...(newFieldInputType === 'section' && {
        referenceSectionId: selectedReferenceSectionId,
        referencePageId: selectedReferenceSectionPageId
      }),
      createdAt: new Date().toISOString().split('T')[0]
    };
    addFieldToSection(selectedPage.id, selectedSectionForField, newField);
    setNewFieldName('');
    setNewFieldKey('');
    setNewFieldInputType('textbox');
    setNewFieldRequired(false);
    setSelectedReferenceSectionId('');
    setSelectedReferenceSectionPageId('');
    setIsFieldDialogOpen(false);
    toast.success('항목이 추가되었습니다');
  };

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

  const moveSection = (dragIndex: number, hoverIndex: number) => {
    if (!selectedPage) return;
    const newSections = [...selectedPage.sections];
    const [draggedSection] = newSections.splice(dragIndex, 1);
    newSections.splice(hoverIndex, 0, draggedSection);
    reorderSections(selectedPage.id, newSections.map(s => s.id));
  };

  const makeMoveFieldHandler = (sectionId: string) => {
    return (dragIndex: number, hoverIndex: number) => {
      if (!selectedPage) return;
      const section = selectedPage.sections.find(s => s.id === sectionId);
      if (!section) return;
      const newFields = [...section.fields];
      const [draggedField] = newFields.splice(dragIndex, 1);
      newFields.splice(hoverIndex, 0, draggedField);
      reorderFields(selectedPage.id, sectionId, newFields.map(f => f.id));
    };
  };

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

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="categories">
            <FolderTree 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="hierarchy">
            <Database className="w-4 h-4 mr-2" />
            계층구조
          </TabsTrigger>
        </TabsList>

        {/* 품목분류 탭 */}
        <TabsContent value="categories" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>품목분류 관리</CardTitle>
              <CardDescription>대분류 → 중분류 → 소분류 3단계 계층 구조</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex gap-2">
                <Input
                  placeholder="대분류명 입력"
                  value={newCategory1}
                  onChange={(e) => setNewCategory1(e.target.value)}
                />
                <Button onClick={handleAddCategory1}><Plus className="w-4 h-4 mr-2" />추가</Button>
              </div>
              <div className="border rounded-lg p-4 space-y-2">
                {Object.entries(itemCategories).map(([cat1, cat2Data]) => (
                  <div key={cat1} className="space-y-2">
                    <div className="flex items-center justify-between bg-background p-2 rounded">
                      <div className="flex items-center gap-2">
                        <Folder className="w-4 h-4" />
                        <span>{cat1}</span>
                      </div>
                      <Button variant="ghost" size="sm" onClick={() => handleDeleteCategory1(cat1)}>
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 단위 탭 */}
        <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="grid grid-cols-2 gap-3">
                {unitOptions.map((option) => (
                  <div key={option.id} className="flex items-center justify-between p-3 border rounded">
                    <div>{option.label}</div>
                    <Button variant="ghost" size="sm" onClick={() => handleDeleteOption('unit', option.id)}>
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </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="grid grid-cols-2 gap-3">
                {materialOptions.map((option) => (
                  <div key={option.id} className="flex items-center justify-between p-3 border rounded">
                    <div>{option.label}</div>
                    <Button variant="ghost" size="sm" onClick={() => handleDeleteOption('material', option.id)}>
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </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="grid grid-cols-2 gap-3">
                {surfaceTreatmentOptions.map((option) => (
                  <div key={option.id} className="flex items-center justify-between p-3 border rounded">
                    <div>{option.label}</div>
                    <Button variant="ghost" size="sm" onClick={() => handleDeleteOption('surface', option.id)}>
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 계층구조 탭 */}
        <TabsContent value="hierarchy" className="space-y-4">
          <div className="grid grid-cols-4 gap-4">
            {/* 페이지 목록 */}
            <Card className="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.map(page => (
                  <button
                    key={page.id}
                    onClick={() => setSelectedPage(page)}
                    className={`w-full text-left p-2 rounded hover:bg-gray-50 ${
                      selectedPage?.id === page.id ? 'bg-blue-50 border border-blue-200' : 'border'
                    }`}
                  >
                    <div className="text-sm">{page.pageName}</div>
                  </button>
                ))}
              </CardContent>
            </Card>

            {/* 계층구조 */}
            <Card className="col-span-3">
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle>{selectedPage?.pageName || '페이지를 선택하세요'}</CardTitle>
                  {selectedPage && (
                    <Button size="sm" onClick={() => setIsSectionDialogOpen(true)}>
                      <Plus className="h-4 w-4 mr-2" />섹션 추가
                    </Button>
                  )}
                </div>
              </CardHeader>
              <CardContent>
                {selectedPage ? (
                  <div className="space-y-4">
                    {selectedPage.sections.map((section) => (
                      <DraggableSection
                        key={section.id}
                        section={section}
                        index={selectedPage.sections.indexOf(section)}
                        pageId={selectedPage.id}
                        isExpanded={expandedSections[section.id] || false}
                        onToggle={() => toggleSection(section.id)}
                        onDelete={() => deleteSection(selectedPage.id, section.id)}
                        onMoveSection={moveSection}
                      >
                        <div className="ml-8 space-y-2">
                          {section.fields.map((field) => (
                            <DraggableField
                              key={field.id}
                              field={field}
                              index={section.fields.indexOf(field)}
                              pageId={selectedPage.id}
                              sectionId={section.id}
                              onDelete={() => deleteField(selectedPage.id, section.id, field.id)}
                              onMoveField={makeMoveFieldHandler(section.id)}
                              allPages={itemPages}
                            />
                          ))}
                          <Button size="sm" variant="outline" onClick={() => {
                            setSelectedSectionForField(section.id);
                            setIsFieldDialogOpen(true);
                          }}>
                            <Plus className="h-3 w-3 mr-1" />항목 추가
                          </Button>
                        </div>
                      </DraggableSection>
                    ))}
                  </div>
                ) : (
                  <p className="text-center text-gray-500">왼쪽에서 페이지를 선택하세요</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>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>페이지명</Label>
              <Input value={newPageName} onChange={(e) => setNewPageName(e.target.value)} />
            </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>
          <DialogHeader>
            <DialogTitle>섹션 추가</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>섹션 제목</Label>
              <Input value={newSectionTitle} onChange={(e) => setNewSectionTitle(e.target.value)} />
            </div>
            <div>
              <Label>설명 (선택)</Label>
              <Textarea value={newSectionDescription} onChange={(e) => setNewSectionDescription(e.target.value)} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsSectionDialogOpen(false)}>취소</Button>
            <Button onClick={handleAddSection}>추가</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 항목 추가 다이얼로그 */}
      <Dialog open={isFieldDialogOpen} onOpenChange={setIsFieldDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>항목 추가</DialogTitle>
            <DialogDescription>
              {newFieldInputType === 'section' && '섹션 참조를 선택하면 해당 섹션의 모든 필드가 포함됩니다'}
            </DialogDescription>
          </DialogHeader>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <Label>항목명</Label>
              <Input value={newFieldName} onChange={(e) => setNewFieldName(e.target.value)} />
            </div>
            <div>
              <Label>필드 키</Label>
              <Input value={newFieldKey} onChange={(e) => setNewFieldKey(e.target.value)} />
            </div>
            <div className="col-span-2">
              <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 === 'section' && (
              <div className="col-span-2 space-y-3">
                <div className="p-3 bg-blue-50 border border-blue-200 rounded">
                  <p className="text-sm text-blue-800">
                    <FileText className="w-4 h-4 inline mr-1" />
                    참조할 섹션을 선택하면 해당 섹션의 모든 필드를 풀세트로 가져옵니다
                  </p>
                </div>
                <div>
                  <Label>참조할 섹션 선택</Label>
                  <Select 
                    value={selectedReferenceSectionId} 
                    onValueChange={(v) => {
                      setSelectedReferenceSectionId(v);
                      const availableSections = getAllAvailableSections();
                      const selected = availableSections.find(s => s.section.id === v);
                      if (selected) {
                        setSelectedReferenceSectionPageId(selected.pageId);
                      }
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="섹션을 선택하세요" />
                    </SelectTrigger>
                    <SelectContent>
                      {getAllAvailableSections().map(({ pageId, pageName, section }) => (
                        <SelectItem key={section.id} value={section.id}>
                          {pageName} → {section.title} ({section.fields.length}개 필드)
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                {selectedReferenceSectionId && (
                  <div className="border rounded p-3 bg-gray-50">
                    <p className="text-sm mb-2">포함될 필드:</p>
                    <div className="space-y-1">
                      {(() => {
                        const section = getAllAvailableSections().find(s => s.section.id === selectedReferenceSectionId);
                        return section?.section.fields.map(field => (
                          <div key={field.id} className="text-sm text-gray-600 flex items-center gap-2">
                            <Badge variant="outline" className="text-xs">{field.property.inputType}</Badge>
                            {field.name}
                          </div>
                        ));
                      })()}
                    </div>
                  </div>
                )}
              </div>
            )}
            {newFieldInputType !== 'section' && (
              <div className="col-span-2 flex items-center gap-2">
                <Switch checked={newFieldRequired} onCheckedChange={setNewFieldRequired} />
                <Label>필수 항목</Label>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setIsFieldDialogOpen(false);
              setSelectedReferenceSectionId('');
              setSelectedReferenceSectionPageId('');
            }}>취소</Button>
            <Button onClick={handleAddField}>추가</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}