import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Checkbox } from "./ui/checkbox";
import { useDrag, useDrop, DndProvider } from "react-dnd";
import { SingletonHTML5Backend } from "../lib/dnd";
import {
  Plus,
  Trash2,
  Save,
  Sparkles,
  LayoutDashboard,
  ShoppingCart,
  Factory,
  Users,
  ClipboardCheck,
  Package,
  Truck,
  Calculator,
  Database,
  Settings,
  Zap,
  Check,
  GripVertical,
  Eye,
  Sliders,
  GitBranch,
  ArrowRight,
  ListOrdered,
  Wand2,
  Move,
} from "lucide-react";
import { toast } from "sonner";

interface MenuAttribute {
  id: string;
  label: string;
  type: "text" | "number" | "date" | "select" | "boolean" | "percentage";
  required: boolean;
  options?: string[];
  defaultValue?: any;
}

interface ProcessStep {
  id: string;
  label: string;
  description: string;
  color: string;
  order: number;
  suggestedAttributes?: MenuAttribute[];
}

interface MenuItem {
  id: string;
  label: string;
  icon: string;
  category: string;
  description: string;
  attributes?: MenuAttribute[];
  process?: ProcessStep[];
}

interface Category {
  id: string;
  name: string;
  icon: string;
  color: string;
}

interface RoleMenu {
  role: string;
  selectedCategories: string[];
  menuItems: string[];
}

const iconMap: { [key: string]: any } = {
  LayoutDashboard,
  ShoppingCart,
  Factory,
  Users,
  ClipboardCheck,
  Package,
  Truck,
  Calculator,
  Database,
  Settings,
};

// 프로세스 단계별 추천 속성
const stepAttributePresets: { [key: string]: MenuAttribute[] } = {
  "planning": [
    { id: "plan-quantity", label: "계획수량", type: "number", required: true, defaultValue: "0" },
    { id: "plan-date", label: "계획일자", type: "date", required: true, defaultValue: "" },
    { id: "plan-person", label: "계획담당자", type: "text", required: false, defaultValue: "" },
  ],
  "material-prep": [
    { id: "material-list", label: "필요자재", type: "text", required: true, defaultValue: "" },
    { id: "material-quantity", label: "자재수량", type: "number", required: true, defaultValue: "0" },
    { id: "material-status", label: "준비상태", type: "select", required: true, options: ["대기", "준비완료", "부족"], defaultValue: "대기" },
  ],
  "start": [
    { id: "start-time", label: "시작시간", type: "date", required: true, defaultValue: "" },
    { id: "worker-count", label: "투입인원", type: "number", required: false, defaultValue: "1" },
    { id: "equipment", label: "사용설비", type: "text", required: false, defaultValue: "" },
  ],
  "in-progress": [
    { id: "current-quantity", label: "현재수량", type: "number", required: true, defaultValue: "0" },
    { id: "progress-rate", label: "진행률", type: "percentage", required: false, defaultValue: "0" },
    { id: "work-status", label: "작업상태", type: "select", required: true, options: ["정상", "지연", "중단"], defaultValue: "정상" },
  ],
  "quality-check": [
    { id: "inspection-result", label: "검사결과", type: "select", required: true, options: ["합격", "불합격", "재검사"], defaultValue: "합격" },
    { id: "defect-rate", label: "불량률", type: "percentage", required: false, defaultValue: "0" },
    { id: "inspector", label: "검사자", type: "text", required: true, defaultValue: "" },
  ],
  "completed": [
    { id: "completion-quantity", label: "완료수량", type: "number", required: true, defaultValue: "0" },
    { id: "completion-time", label: "완료시간", type: "date", required: true, defaultValue: "" },
    { id: "quality-passed", label: "품질합격", type: "boolean", required: true, defaultValue: "true" },
  ],
  "request": [
    { id: "request-item", label: "요청항목", type: "text", required: true, defaultValue: "" },
    { id: "request-date", label: "요청일자", type: "date", required: true, defaultValue: "" },
    { id: "requester", label: "요청자", type: "text", required: true, defaultValue: "" },
  ],
  "sampling": [
    { id: "sample-quantity", label: "샘플수량", type: "number", required: true, defaultValue: "0" },
    { id: "sampling-method", label: "채취방법", type: "text", required: false, defaultValue: "" },
  ],
  "testing": [
    { id: "test-items", label: "검사항목", type: "text", required: true, defaultValue: "" },
    { id: "test-method", label: "검사방법", type: "text", required: false, defaultValue: "" },
  ],
  "judgment": [
    { id: "pass-rate", label: "합격률", type: "percentage", required: true, defaultValue: "0" },
    { id: "judgment-result", label: "판정결과", type: "select", required: true, options: ["합격", "불합격", "조건부합격"], defaultValue: "합격" },
  ],
  "report": [
    { id: "report-number", label: "보고서번호", type: "text", required: true, defaultValue: "" },
    { id: "report-date", label: "작성일자", type: "date", required: true, defaultValue: "" },
  ],
  "lead": [
    { id: "lead-name", label: "고객명", type: "text", required: true, defaultValue: "" },
    { id: "lead-company", label: "회사명", type: "text", required: true, defaultValue: "" },
    { id: "lead-source", label: "유입경로", type: "select", required: false, options: ["웹사이트", "소개", "광고", "기타"], defaultValue: "웹사이트" },
  ],
  "consultation": [
    { id: "consultation-date", label: "상담일자", type: "date", required: true, defaultValue: "" },
    { id: "consultation-notes", label: "상담내용", type: "text", required: true, defaultValue: "" },
  ],
  "proposal": [
    { id: "proposal-amount", label: "제안금액", type: "number", required: true, defaultValue: "0" },
    { id: "proposal-date", label: "제안일자", type: "date", required: true, defaultValue: "" },
  ],
  "negotiation": [
    { id: "negotiation-status", label: "협상상태", type: "select", required: true, options: ["진행중", "보류", "결렬"], defaultValue: "진행중" },
    { id: "discount-rate", label: "할인율", type: "percentage", required: false, defaultValue: "0" },
  ],
  "contract": [
    { id: "contract-amount", label: "계약금액", type: "number", required: true, defaultValue: "0" },
    { id: "contract-date", label: "계약일자", type: "date", required: true, defaultValue: "" },
    { id: "contract-period", label: "계약기간", type: "text", required: false, defaultValue: "" },
  ],
};

// 산업별 프로세스 프리셋
const processPresets: { [key: string]: { [key: string]: ProcessStep[] } } = {
  production: {
    default: [
      { id: "planning", label: "계획수립", description: "생산계획 수립", color: "#3B82F6", order: 1, suggestedAttributes: stepAttributePresets["planning"] },
      { id: "material-prep", label: "자재준비", description: "필요 자재 준비", color: "#10B981", order: 2, suggestedAttributes: stepAttributePresets["material-prep"] },
      { id: "start", label: "생산착수", description: "생산 시작", color: "#F59E0B", order: 3, suggestedAttributes: stepAttributePresets["start"] },
      { id: "in-progress", label: "생산진행", description: "생산 진행중", color: "#8B5CF6", order: 4, suggestedAttributes: stepAttributePresets["in-progress"] },
      { id: "quality-check", label: "품질검사", description: "품질 검사", color: "#EF4444", order: 5, suggestedAttributes: stepAttributePresets["quality-check"] },
      { id: "completed", label: "완료", description: "생산 완료", color: "#06B6D4", order: 6, suggestedAttributes: stepAttributePresets["completed"] },
    ],
  },
  quality: {
    default: [
      { id: "request", label: "검사요청", description: "검사 요청", color: "#3B82F6", order: 1, suggestedAttributes: stepAttributePresets["request"] },
      { id: "sampling", label: "샘플채취", description: "샘플 채취", color: "#10B981", order: 2, suggestedAttributes: stepAttributePresets["sampling"] },
      { id: "testing", label: "검사진행", description: "검사 진행중", color: "#F59E0B", order: 3, suggestedAttributes: stepAttributePresets["testing"] },
      { id: "judgment", label: "결과판정", description: "합격/불합격 판정", color: "#EF4444", order: 4, suggestedAttributes: stepAttributePresets["judgment"] },
      { id: "report", label: "보고서작성", description: "검사 보고서", color: "#06B6D4", order: 5, suggestedAttributes: stepAttributePresets["report"] },
    ],
  },
  sales: {
    default: [
      { id: "lead", label: "리드생성", description: "잠재고객 등록", color: "#3B82F6", order: 1, suggestedAttributes: stepAttributePresets["lead"] },
      { id: "consultation", label: "상담", description: "고객 상담", color: "#10B981", order: 2, suggestedAttributes: stepAttributePresets["consultation"] },
      { id: "proposal", label: "제안", description: "제안서 제출", color: "#F59E0B", order: 3, suggestedAttributes: stepAttributePresets["proposal"] },
      { id: "negotiation", label: "협상", description: "가격/조건 협상", color: "#8B5CF6", order: 4, suggestedAttributes: stepAttributePresets["negotiation"] },
      { id: "contract", label: "계약체결", description: "계약 완료", color: "#06B6D4", order: 5, suggestedAttributes: stepAttributePresets["contract"] },
    ],
  },
};

// 드래그 가능한 프로세스 카드 컴포넌트
interface DraggableProcessStepProps {
  step: ProcessStep;
  index: number;
  moveStep: (dragIndex: number, hoverIndex: number) => void;
  onDelete: () => void;
  onApplyAttributes: () => void;
}

const DraggableProcessStep = ({ step, index, moveStep, onDelete, onApplyAttributes }: DraggableProcessStepProps) => {
  const [{ isDragging }, drag, preview] = useDrag({
    type: "PROCESS_STEP",
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  const [, drop] = useDrop({
    accept: "PROCESS_STEP",
    hover: (item: { index: number }) => {
      if (item.index !== index) {
        moveStep(item.index, index);
        item.index = index;
      }
    },
  });

  return (
    <div ref={(node) => drag(drop(node))} style={{ opacity: isDragging ? 0.5 : 1 }}>
      <div className="flex items-center gap-3 p-4 border rounded-lg hover:bg-gray-50 transition-colors group cursor-move">
        <GripVertical className="w-5 h-5 text-gray-400" />
        <div
          className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold flex-shrink-0"
          style={{ backgroundColor: step.color }}
        >
          {step.order}
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <p className="font-semibold">{step.label}</p>
            {step.suggestedAttributes && step.suggestedAttributes.length > 0 && (
              <Badge variant="outline" className="text-xs">
                {step.suggestedAttributes.length}개 추천 속성
              </Badge>
            )}
          </div>
          <p className="text-sm text-gray-600">{step.description}</p>
        </div>
        <div className="flex gap-2 opacity-0 group-hover:opacity-100">
          {step.suggestedAttributes && step.suggestedAttributes.length > 0 && (
            <Button
              variant="ghost"
              size="sm"
              onClick={onApplyAttributes}
              className="text-purple-600 hover:text-purple-700 hover:bg-purple-50"
              title="추천 속성 자동 추가"
            >
              <Wand2 className="w-4 h-4" />
            </Button>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={onDelete}
            className="text-red-500 hover:text-red-700 hover:bg-red-50"
          >
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </div>
  );
};

// 드래그 가능한 메뉴 아이템 컴포넌트
interface DraggableMenuItemProps {
  menu: MenuItem;
  category: Category;
  isSelected: boolean;
  onToggle: () => void;
  onMove: (newCategoryId: string) => void;
}

const DraggableMenuItem = ({ menu, category, isSelected, onToggle, onMove }: DraggableMenuItemProps) => {
  const [{ isDragging }, drag] = useDrag({
    type: "MENU_ITEM",
    item: { menuId: menu.id, currentCategory: menu.category },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  const IconComponent = iconMap[menu.icon] || Settings;

  return (
    <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
      <button
        onClick={onToggle}
        className={`p-3 rounded-lg border-2 transition-all cursor-move w-full ${
          isSelected
            ? "border-blue-500 bg-blue-50 shadow-sm"
            : "border-gray-200 hover:border-blue-300 hover:bg-gray-50"
        }`}
      >
        <div className="flex items-center gap-3">
          <GripVertical className="w-4 h-4 text-gray-400 flex-shrink-0" />
          <div
            className="w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0"
            style={{ backgroundColor: `${category.color}20` }}
          >
            <IconComponent className="w-5 h-5" style={{ color: category.color }} />
          </div>
          <div className="flex-1 text-left">
            <p className="text-sm font-medium">{menu.label}</p>
            <p className="text-xs text-gray-500">{menu.description}</p>
          </div>
          {isSelected && <Check className="w-5 h-5 text-blue-500 flex-shrink-0" />}
        </div>
      </button>
    </div>
  );
};

// 드래그 가능한 카테고리 섹션 컴포넌트
interface DraggableCategorySectionProps {
  category: Category;
  menuItems: MenuItem[];
  roleMenu: RoleMenu;
  onMenuToggle: (menuId: string) => void;
  onMenuMove: (menuId: string, newCategoryId: string) => void;
}

const DraggableCategorySection = ({
  category,
  menuItems,
  roleMenu,
  onMenuToggle,
  onMenuMove,
}: DraggableCategorySectionProps) => {
  const [{ isOver }, drop] = useDrop({
    accept: "MENU_ITEM",
    drop: (item: { menuId: string; currentCategory: string }) => {
      if (item.currentCategory !== category.id) {
        onMenuMove(item.menuId, category.id);
      }
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
    }),
  });

  const IconComponent = iconMap[category.icon] || Settings;

  return (
    <div
      ref={drop}
      className={`border-2 rounded-lg p-4 transition-all ${
        isOver
          ? "border-blue-500 bg-blue-50 shadow-lg"
          : "border-gray-200 bg-white"
      }`}
    >
      <div className="flex items-center gap-3 mb-4">
        <div
          className="w-10 h-10 rounded-lg flex items-center justify-center"
          style={{ backgroundColor: `${category.color}20` }}
        >
          <IconComponent className="w-5 h-5" style={{ color: category.color }} />
        </div>
        <div className="flex-1">
          <h4 className="font-semibold">{category.name}</h4>
          <p className="text-xs text-gray-500">
            {menuItems.filter((m) => roleMenu.menuItems.includes(m.id)).length} / {menuItems.length}개 메뉴 선택됨
          </p>
        </div>
        {isOver && (
          <Badge className="bg-blue-500">
            <Move className="w-3 h-3 mr-1" />
            여기에 놓기
          </Badge>
        )}
      </div>

      {menuItems.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {menuItems.map((menu) => (
            <DraggableMenuItem
              key={menu.id}
              menu={menu}
              category={category}
              isSelected={roleMenu.menuItems.includes(menu.id)}
              onToggle={() => onMenuToggle(menu.id)}
              onMove={(newCategoryId) => onMenuMove(menu.id, newCategoryId)}
            />
          ))}
        </div>
      ) : (
        <div className="text-center py-8 border-2 border-dashed rounded-lg bg-gray-50">
          <p className="text-sm text-gray-500">이 카테고리에는 메뉴가 없습니다</p>
          <p className="text-xs text-gray-400 mt-1">다른 카테고리에서 메뉴를 드래그하여 추가하세요</p>
        </div>
      )}
    </div>
  );
};

export default function MenuCustomization() {
  const [categories, setCategories] = useState<Category[]>([
    { id: "dashboard", name: "대시보드", icon: "LayoutDashboard", color: "#3B82F6" },
    { id: "sales", name: "판매관리", icon: "ShoppingCart", color: "#10B981" },
    { id: "production", name: "생산관리", icon: "Factory", color: "#F59E0B" },
    { id: "quality", name: "품질관리", icon: "ClipboardCheck", color: "#EF4444" },
    { id: "materials", name: "자재관리", icon: "Package", color: "#8B5CF6" },
    { id: "shipping", name: "출하관리", icon: "Truck", color: "#06B6D4" },
    { id: "accounting", name: "회계관리", icon: "Calculator", color: "#EC4899" },
    { id: "master", name: "기준정보", icon: "Database", color: "#6366F1" },
  ]);

  const [menuItems, setMenuItems] = useState<MenuItem[]>([
    { id: "dashboard", label: "대시보드", icon: "LayoutDashboard", category: "dashboard", description: "전체 현황 개요" },
    { id: "sales", label: "판매관리", icon: "ShoppingCart", category: "sales", description: "주문 및 판매 관리" },
    { id: "production", label: "생산관리", icon: "Factory", category: "production", description: "생산 현황 및 계획" },
    { id: "quality", label: "품질관리", icon: "ClipboardCheck", category: "quality", description: "품질 검사 및 분석" },
    { id: "materials", label: "자재관리", icon: "Package", category: "materials", description: "재고 및 자재 관리" },
    { id: "shipping", label: "출하관리", icon: "Truck", category: "shipping", description: "출하 및 배송 관리" },
    { id: "accounting", label: "회계관리", icon: "Calculator", category: "accounting", description: "재무 및 회계" },
    { id: "master", label: "기준정보", icon: "Database", category: "master", description: "마스터 데이터 관리" },
  ]);

  const [roleMenus, setRoleMenus] = useState<RoleMenu[]>([
    { 
      role: "CEO", 
      selectedCategories: ["dashboard", "sales", "production", "quality", "accounting"],
      menuItems: ["dashboard", "sales", "production", "quality", "accounting"] 
    },
    { 
      role: "ProductionManager", 
      selectedCategories: ["dashboard", "production", "quality", "materials"],
      menuItems: ["dashboard", "production", "quality", "materials"] 
    },
    { 
      role: "Worker", 
      selectedCategories: ["production"],
      menuItems: ["production"] 
    },
    { 
      role: "Sales", 
      selectedCategories: ["dashboard", "sales", "shipping"],
      menuItems: ["dashboard", "sales", "shipping"] 
    },
    { 
      role: "SystemAdmin", 
      selectedCategories: ["dashboard", "master"],
      menuItems: ["dashboard", "master"] 
    },
  ]);

  const [selectedRole, setSelectedRole] = useState("CEO");
  const [selectedMenuItem, setSelectedMenuItem] = useState<string | null>(null);
  const [selectedMenuForProcess, setSelectedMenuForProcess] = useState<string | null>(null);
  
  const [isAddCategoryOpen, setIsAddCategoryOpen] = useState(false);
  const [isAddMenuItemOpen, setIsAddMenuItemOpen] = useState(false);
  const [isAttributeModalOpen, setIsAttributeModalOpen] = useState(false);
  const [isProcessModalOpen, setIsProcessModalOpen] = useState(false);

  const [newCategory, setNewCategory] = useState({ name: "", icon: "Settings", color: "#3B82F6" });
  const [newMenuItem, setNewMenuItem] = useState({ label: "", icon: "Settings", category: "", description: "" });
  const [newAttribute, setNewAttribute] = useState<MenuAttribute>({
    id: "",
    label: "",
    type: "text",
    required: false,
    options: [],
    defaultValue: ""
  });
  const [newProcessStep, setNewProcessStep] = useState<ProcessStep>({
    id: "",
    label: "",
    description: "",
    color: "#3B82F6",
    order: 1
  });

  // 프로세스 순서 변경
  const moveProcessStep = (menuId: string, dragIndex: number, hoverIndex: number) => {
    setMenuItems(
      menuItems.map((item) => {
        if (item.id === menuId && item.process) {
          const updatedProcess = [...item.process];
          const [draggedStep] = updatedProcess.splice(dragIndex, 1);
          updatedProcess.splice(hoverIndex, 0, draggedStep);
          
          // 순서 재정렬
          const reorderedProcess = updatedProcess.map((step, index) => ({
            ...step,
            order: index + 1,
          }));
          
          return { ...item, process: reorderedProcess };
        }
        return item;
      })
    );
  };

  // 프로세스 단계의 추천 속성을 메뉴에 추가
  const applyStepAttributes = (menuId: string, step: ProcessStep) => {
    if (!step.suggestedAttributes || step.suggestedAttributes.length === 0) {
      toast.error("이 단계에는 추천 속성이 없습니다.");
      return;
    }

    setMenuItems(
      menuItems.map((item) => {
        if (item.id === menuId) {
          const existingAttributes = item.attributes || [];
          const newAttributes = step.suggestedAttributes!.filter(
            (newAttr) => !existingAttributes.some((existing) => existing.id === newAttr.id)
          );

          if (newAttributes.length === 0) {
            toast.info("모든 추천 속성이 이미 추가되어 있습니다.");
            return item;
          }

          toast.success(`${newAttributes.length}개의 속성이 자동으로 추가되었습니다!`);
          return {
            ...item,
            attributes: [...existingAttributes, ...newAttributes],
          };
        }
        return item;
      })
    );
  };

  // 전체 프로세스의 모든 추천 속성을 한번에 추가
  const applyAllProcessAttributes = (menuId: string) => {
    const currentItem = menuItems.find((m) => m.id === menuId);
    if (!currentItem || !currentItem.process || currentItem.process.length === 0) {
      toast.error("프로세스가 설정되지 않았습니다.");
      return;
    }

    const allSuggestedAttributes: MenuAttribute[] = [];
    currentItem.process.forEach((step) => {
      if (step.suggestedAttributes) {
        allSuggestedAttributes.push(...step.suggestedAttributes);
      }
    });

    if (allSuggestedAttributes.length === 0) {
      toast.error("추천 속성이 없습니다.");
      return;
    }

    setMenuItems(
      menuItems.map((item) => {
        if (item.id === menuId) {
          const existingAttributes = item.attributes || [];
          const newAttributes = allSuggestedAttributes.filter(
            (newAttr) => !existingAttributes.some((existing) => existing.id === newAttr.id)
          );

          if (newAttributes.length === 0) {
            toast.info("모든 추천 속성이 이미 추가되어 있습니다.");
            return item;
          }

          toast.success(`${newAttributes.length}개의 속성이 자동으로 추가되었습니다!`);
          return {
            ...item,
            attributes: [...existingAttributes, ...newAttributes],
          };
        }
        return item;
      })
    );
  };

  // 핸들러 함수들
  const handleAddCategory = () => {
    if (!newCategory.name) {
      toast.error("카테고리 이름을 입력하세요.");
      return;
    }

    const category: Category = {
      id: newCategory.name.toLowerCase().replace(/\s+/g, "-"),
      name: newCategory.name,
      icon: newCategory.icon,
      color: newCategory.color,
    };

    setCategories([...categories, category]);
    setNewCategory({ name: "", icon: "Settings", color: "#3B82F6" });
    setIsAddCategoryOpen(false);
    toast.success(`카테고리 "${category.name}"가 추가되었습니다.`);
  };

  const handleAddMenuItem = () => {
    if (!newMenuItem.label || !newMenuItem.category) {
      toast.error("메뉴 항목 정보를 모두 입력하세요.");
      return;
    }

    const menuItem: MenuItem = {
      id: newMenuItem.label.toLowerCase().replace(/\s+/g, "-"),
      label: newMenuItem.label,
      icon: newMenuItem.icon,
      category: newMenuItem.category,
      description: newMenuItem.description,
    };

    setMenuItems([...menuItems, menuItem]);
    setNewMenuItem({ label: "", icon: "Settings", category: "", description: "" });
    setIsAddMenuItemOpen(false);
    toast.success(`메뉴 항목 "${menuItem.label}"이 추가되었습니다.`);
  };

  const handleAddAttribute = () => {
    if (!selectedMenuItem || !newAttribute.label) {
      toast.error("속성 이름을 입력하세요.");
      return;
    }

    const attribute: MenuAttribute = {
      ...newAttribute,
      id: newAttribute.label.toLowerCase().replace(/\s+/g, "-"),
    };

    setMenuItems(
      menuItems.map((item) =>
        item.id === selectedMenuItem
          ? { ...item, attributes: [...(item.attributes || []), attribute] }
          : item
      )
    );

    setNewAttribute({
      id: "",
      label: "",
      type: "text",
      required: false,
      options: [],
      defaultValue: ""
    });

    toast.success(`속성 "${attribute.label}"이 추가되었습니다.`);
  };

  const handleDeleteAttribute = (menuItemId: string, attributeId: string) => {
    setMenuItems(
      menuItems.map((item) =>
        item.id === menuItemId
          ? { ...item, attributes: item.attributes?.filter((attr) => attr.id !== attributeId) }
          : item
      )
    );
    toast.success("속성이 삭제되었습니다.");
  };

  const handleAddProcessStep = () => {
    if (!selectedMenuForProcess || !newProcessStep.label) {
      toast.error("프로세스 단계 이름을 입력하세요.");
      return;
    }

    const currentItem = menuItems.find((m) => m.id === selectedMenuForProcess);
    const currentSteps = currentItem?.process || [];

    const step: ProcessStep = {
      ...newProcessStep,
      id: newProcessStep.label.toLowerCase().replace(/\s+/g, "-"),
      order: currentSteps.length + 1,
    };

    setMenuItems(
      menuItems.map((item) =>
        item.id === selectedMenuForProcess
          ? { ...item, process: [...currentSteps, step] }
          : item
      )
    );

    setNewProcessStep({
      id: "",
      label: "",
      description: "",
      color: "#3B82F6",
      order: 1
    });

    toast.success(`프로세스 단계 "${step.label}"이 추가되었습니다.`);
  };

  const handleDeleteProcessStep = (menuItemId: string, stepId: string) => {
    setMenuItems(
      menuItems.map((item) => {
        if (item.id === menuItemId) {
          const updatedProcess = item.process?.filter((s) => s.id !== stepId)
            .map((s, index) => ({ ...s, order: index + 1 }));
          return { ...item, process: updatedProcess };
        }
        return item;
      })
    );
    toast.success("프로세스 단계가 삭제되었습니다.");
  };

  const handleApplyProcessPreset = (menuId: string, presetType: string) => {
    const preset = processPresets[menuId]?.[presetType] || processPresets.production.default;
    
    setMenuItems(
      menuItems.map((item) =>
        item.id === menuId
          ? { ...item, process: [...preset] }
          : item
      )
    );

    toast.success("프로세스 프리셋이 적용되었습니다!");
  };

  const handleSaveConfiguration = () => {
    const config = {
      categories,
      menuItems,
      roleMenus,
      timestamp: new Date().toISOString(),
    };

    localStorage.setItem("menuConfiguration", JSON.stringify(config));
    toast.success("메뉴 구성이 저장되었습니다!");
  };

  const getAttributeTypeLabel = (type: string) => {
    const labels: { [key: string]: string } = {
      text: "텍스트",
      number: "숫자",
      date: "날짜",
      select: "선택",
      boolean: "예/아니오",
      percentage: "퍼센트",
    };
    return labels[type] || type;
  };

  const getRoleLabel = (role: string) => {
    const labels: { [key: string]: string } = {
      CEO: "대표이사",
      ProductionManager: "생산관리자",
      Worker: "생산작업자",
      Sales: "영업사원",
      SystemAdmin: "시스템관리자",
    };
    return labels[role] || role;
  };

  return (
    <DndProvider backend={SingletonHTML5Backend}>
      <div className="space-y-6 p-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-3xl font-bold text-gray-900">메뉴 커스터마이징</h2>
            <p className="text-sm text-gray-600 mt-1">카테고리, 메뉴, 속성, 프로세스를 자유롭게 구성하세요</p>
          </div>
          <div className="flex gap-3">
            <Button onClick={handleSaveConfiguration} variant="outline">
              <Save className="w-4 h-4 mr-2" />
              저장
            </Button>
          </div>
        </div>

        <Tabs defaultValue="categories" className="space-y-6">
          <TabsList className="grid w-full grid-cols-5">
            <TabsTrigger value="categories">카테고리</TabsTrigger>
            <TabsTrigger value="menu-items">메뉴 항목</TabsTrigger>
            <TabsTrigger value="attributes">속성 관리</TabsTrigger>
            <TabsTrigger value="process">프로세스</TabsTrigger>
            <TabsTrigger value="role-assignment">역할 할당</TabsTrigger>
          </TabsList>

          {/* Categories Tab */}
          <TabsContent value="categories" className="space-y-4">
            <div className="flex justify-between items-center">
              <p className="text-sm text-gray-600">총 {categories.length}개의 카테고리</p>
              <Button onClick={() => setIsAddCategoryOpen(true)} size="sm">
                <Plus className="w-4 h-4 mr-2" />
                카테고리 추가
              </Button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {categories.map((category) => {
                const IconComponent = iconMap[category.icon] || Settings;
                return (
                  <Card key={category.id} className="hover:shadow-lg transition-shadow">
                    <CardContent className="pt-6">
                      <div className="flex items-center justify-center mb-4">
                        <div className="w-16 h-16 rounded-2xl flex items-center justify-center" style={{ backgroundColor: `${category.color}20` }}>
                          <IconComponent className="w-8 h-8" style={{ color: category.color }} />
                        </div>
                      </div>
                      <h3 className="font-semibold text-center">{category.name}</h3>
                      <p className="text-xs text-gray-500 text-center mt-1">{category.id}</p>
                      <div className="mt-4 pt-4 border-t">
                        <p className="text-xs text-gray-500 text-center">
                          메뉴: {menuItems.filter((m) => m.category === category.id).length}개
                        </p>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </TabsContent>

          {/* Menu Items Tab */}
          <TabsContent value="menu-items" className="space-y-4">
            <div className="flex justify-between items-center">
              <p className="text-sm text-gray-600">총 {menuItems.length}개의 메뉴 항목</p>
              <Button onClick={() => setIsAddMenuItemOpen(true)} size="sm">
                <Plus className="w-4 h-4 mr-2" />
                메뉴 항목 추가
              </Button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {menuItems.map((item) => {
                const IconComponent = iconMap[item.icon] || Settings;
                const category = categories.find((c) => c.id === item.category);
                return (
                  <Card key={item.id} className="hover:shadow-lg transition-shadow">
                    <CardHeader>
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-12 rounded-xl flex items-center justify-center" style={{ backgroundColor: `${category?.color}20` }}>
                          <IconComponent className="w-6 h-6" style={{ color: category?.color }} />
                        </div>
                        <div className="flex-1">
                          <CardTitle className="text-lg">{item.label}</CardTitle>
                          <CardDescription className="text-xs">{item.description}</CardDescription>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="space-y-2">
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-gray-600">속성:</span>
                          <Badge variant="secondary">{item.attributes?.length || 0}개</Badge>
                        </div>
                        <div className="flex items-center justify-between text-sm">
                          <span className="text-gray-600">프로세스:</span>
                          <Badge variant="secondary">{item.process?.length || 0}단계</Badge>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </TabsContent>

          {/* Attributes Tab */}
          <TabsContent value="attributes" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle>속성 관리</CardTitle>
                <CardDescription>각 메뉴에서 사용할 데이터 속성을 정의하세요</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="flex items-center gap-4">
                  <Label className="min-w-24">메뉴 선택:</Label>
                  <Select value={selectedMenuItem || ""} onValueChange={setSelectedMenuItem}>
                    <SelectTrigger className="flex-1 max-w-md">
                      <SelectValue placeholder="메뉴를 선택하세요" />
                    </SelectTrigger>
                    <SelectContent>
                      {menuItems.map((item) => {
                        const IconComponent = iconMap[item.icon] || Settings;
                        return (
                          <SelectItem key={item.id} value={item.id}>
                            <div className="flex items-center gap-2">
                              <IconComponent className="w-4 h-4" />
                              {item.label}
                            </div>
                          </SelectItem>
                        );
                      })}
                    </SelectContent>
                  </Select>
                  {selectedMenuItem && (
                    <Button onClick={() => setIsAttributeModalOpen(true)} size="sm">
                      <Plus className="w-4 h-4 mr-2" />
                      속성 추가
                    </Button>
                  )}
                </div>

                {selectedMenuItem ? (
                  <div className="border rounded-lg p-6">
                    <h3 className="font-semibold mb-4">
                      {menuItems.find((m) => m.id === selectedMenuItem)?.label} - 속성 목록
                    </h3>
                    {(() => {
                      const item = menuItems.find((m) => m.id === selectedMenuItem);
                      const attributes = item?.attributes || [];

                      if (attributes.length === 0) {
                        return (
                          <div className="text-center py-12 border-2 border-dashed rounded-xl bg-gray-50">
                            <Sliders className="w-12 h-12 mx-auto text-gray-400 mb-3" />
                            <p className="text-gray-600">아직 속성이 없습니다</p>
                            <p className="text-sm text-gray-500 mt-1">
                              "속성 추가" 버튼을 클릭하거나 프로세스에서 자동 추가하세요
                            </p>
                          </div>
                        );
                      }

                      return (
                        <div className="space-y-3">
                          {attributes.map((attr) => (
                            <div
                              key={attr.id}
                              className="p-4 border rounded-lg hover:bg-gray-50 transition-colors group flex items-start justify-between"
                            >
                              <div className="flex-1">
                                <div className="flex items-center gap-3 mb-2">
                                  <p className="font-semibold">{attr.label}</p>
                                  <Badge variant="outline">{getAttributeTypeLabel(attr.type)}</Badge>
                                  {attr.required && <Badge className="bg-red-500">필수</Badge>}
                                </div>
                                {attr.type === "select" && attr.options && attr.options.length > 0 && (
                                  <p className="text-sm text-gray-600">
                                    옵션: {attr.options.join(", ")}
                                  </p>
                                )}
                                {attr.defaultValue && (
                                  <p className="text-sm text-gray-500">
                                    기본값: {String(attr.defaultValue)}
                                  </p>
                                )}
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleDeleteAttribute(selectedMenuItem, attr.id)}
                                className="opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-700"
                              >
                                <Trash2 className="w-4 h-4" />
                              </Button>
                            </div>
                          ))}
                        </div>
                      );
                    })()}
                  </div>
                ) : (
                  <div className="text-center py-12 border-2 border-dashed rounded-xl bg-gray-50">
                    <Database className="w-12 h-12 mx-auto text-gray-400 mb-3" />
                    <p className="text-gray-600">메뉴를 선택하여 속성을 관리하세요</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Process Tab */}
          <TabsContent value="process" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <GitBranch className="w-5 h-5" />
                  프로세스 관리
                </CardTitle>
                <CardDescription>
                  각 메뉴의 업무 프로세스를 정의하세요 • 드래그로 순서 변경 • 마법봉 아이콘으로 속성 자동 추가
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="flex items-center gap-4">
                  <Label className="min-w-24">메뉴 선택:</Label>
                  <Select value={selectedMenuForProcess || ""} onValueChange={setSelectedMenuForProcess}>
                    <SelectTrigger className="flex-1 max-w-md">
                      <SelectValue placeholder="메뉴를 선택하세요" />
                    </SelectTrigger>
                    <SelectContent>
                      {menuItems.map((item) => {
                        const IconComponent = iconMap[item.icon] || Settings;
                        return (
                          <SelectItem key={item.id} value={item.id}>
                            <div className="flex items-center gap-2">
                              <IconComponent className="w-4 h-4" />
                              {item.label}
                            </div>
                          </SelectItem>
                        );
                      })}
                    </SelectContent>
                  </Select>
                  {selectedMenuForProcess && (
                    <div className="flex gap-2">
                      <Button onClick={() => setIsProcessModalOpen(true)} size="sm">
                        <Plus className="w-4 h-4 mr-2" />
                        단계 추가
                      </Button>
                      {processPresets[selectedMenuForProcess] && (
                        <Button
                          onClick={() => handleApplyProcessPreset(selectedMenuForProcess, "default")}
                          size="sm"
                          variant="outline"
                        >
                          <Sparkles className="w-4 h-4 mr-2" />
                          프리셋 적용
                        </Button>
                      )}
                      {(() => {
                        const item = menuItems.find((m) => m.id === selectedMenuForProcess);
                        const hasProcess = item?.process && item.process.length > 0;
                        const hasSuggestedAttributes = hasProcess && item.process.some((s) => s.suggestedAttributes && s.suggestedAttributes.length > 0);
                        
                        return hasSuggestedAttributes && (
                          <Button
                            onClick={() => applyAllProcessAttributes(selectedMenuForProcess)}
                            size="sm"
                            className="bg-purple-600 hover:bg-purple-700"
                          >
                            <Wand2 className="w-4 h-4 mr-2" />
                            전체 속성 자동 추가
                          </Button>
                        );
                      })()}
                    </div>
                  )}
                </div>

                {selectedMenuForProcess ? (
                  <div className="border rounded-lg p-6">
                    <h3 className="font-semibold mb-4 flex items-center gap-2">
                      <Move className="w-5 h-5 text-purple-600" />
                      {menuItems.find((m) => m.id === selectedMenuForProcess)?.label} - 프로세스 단계 (드래그로 순서 변경)
                    </h3>
                    {(() => {
                      const item = menuItems.find((m) => m.id === selectedMenuForProcess);
                      const steps = item?.process || [];

                      if (steps.length === 0) {
                        return (
                          <div className="text-center py-12 border-2 border-dashed rounded-xl bg-gray-50">
                            <GitBranch className="w-12 h-12 mx-auto text-gray-400 mb-3" />
                            <p className="text-gray-600">아직 프로세스 단계가 없습니다</p>
                            <p className="text-sm text-gray-500 mt-1">
                              "단계 추가" 또는 "프리셋 적용" 버튼을 클릭하세요
                            </p>
                          </div>
                        );
                      }

                      return (
                        <div className="space-y-3">
                          {steps
                            .sort((a, b) => a.order - b.order)
                            .map((step, index) => (
                              <div key={step.id}>
                                <DraggableProcessStep
                                  step={step}
                                  index={index}
                                  moveStep={(dragIndex, hoverIndex) =>
                                    moveProcessStep(selectedMenuForProcess, dragIndex, hoverIndex)
                                  }
                                  onDelete={() => handleDeleteProcessStep(selectedMenuForProcess, step.id)}
                                  onApplyAttributes={() => applyStepAttributes(selectedMenuForProcess, step)}
                                />
                                {index < steps.length - 1 && (
                                  <div className="flex justify-center my-2">
                                    <ArrowRight className="w-5 h-5 text-gray-400" />
                                  </div>
                                )}
                              </div>
                            ))}
                        </div>
                      );
                    })()}
                  </div>
                ) : (
                  <div className="text-center py-12 border-2 border-dashed rounded-xl bg-gray-50">
                    <GitBranch className="w-12 h-12 mx-auto text-gray-400 mb-3" />
                    <p className="text-gray-600">메뉴를 선택하여 프로세스를 관리하세요</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* Role Assignment Tab */}
          <TabsContent value="role-assignment" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle>역할별 카테고리 및 메뉴 할당</CardTitle>
                <CardDescription>
                  각 역할에 표시할 카테고리와 메뉴를 선택하세요 • 메뉴를 드래그하여 카테고리 이동 가능
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-8">
                  {roleMenus.map((roleMenu) => (
                    <div key={roleMenu.role} className="border-2 rounded-xl p-6 bg-gradient-to-br from-gray-50 to-white">
                      <div className="flex items-center justify-between mb-6">
                        <div>
                          <h3 className="text-xl font-bold">{getRoleLabel(roleMenu.role)}</h3>
                          <p className="text-sm text-gray-500 mt-1">
                            {roleMenu.selectedCategories.length}개 카테고리 • {roleMenu.menuItems.length}개 메뉴
                          </p>
                        </div>
                      </div>

                      {/* 카테고리 선택 */}
                      <div className="mb-6">
                        <Label className="text-sm font-semibold mb-3 block">카테고리 선택</Label>
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                          {categories.map((category) => {
                            const isSelected = roleMenu.selectedCategories.includes(category.id);
                            const IconComponent = iconMap[category.icon] || Settings;
                            
                            return (
                              <button
                                key={category.id}
                                onClick={() => {
                                  setRoleMenus(
                                    roleMenus.map((rm) => {
                                      if (rm.role === roleMenu.role) {
                                        const newSelectedCategories = isSelected
                                          ? rm.selectedCategories.filter((id) => id !== category.id)
                                          : [...rm.selectedCategories, category.id];
                                        
                                        // 카테고리 해제 시 해당 카테고리의 모든 메뉴도 제거
                                        const newMenuItems = isSelected
                                          ? rm.menuItems.filter((menuId) => {
                                              const menu = menuItems.find((m) => m.id === menuId);
                                              return menu?.category !== category.id;
                                            })
                                          : rm.menuItems;
                                        
                                        return {
                                          ...rm,
                                          selectedCategories: newSelectedCategories,
                                          menuItems: newMenuItems,
                                        };
                                      }
                                      return rm;
                                    })
                                  );
                                }}
                                className={`p-3 rounded-lg border-2 transition-all ${
                                  isSelected
                                    ? "border-blue-500 bg-blue-50 shadow-md"
                                    : "border-gray-200 hover:border-blue-300 hover:bg-gray-50"
                                }`}
                              >
                                <div className="flex flex-col items-center gap-2">
                                  <div
                                    className="w-12 h-12 rounded-xl flex items-center justify-center"
                                    style={{ backgroundColor: `${category.color}20` }}
                                  >
                                    <IconComponent className="w-6 h-6" style={{ color: category.color }} />
                                  </div>
                                  <p className="text-xs font-semibold text-center">{category.name}</p>
                                  {isSelected && <Check className="w-4 h-4 text-blue-500" />}
                                </div>
                              </button>
                            );
                          })}
                        </div>
                      </div>

                      {/* 선택한 카테고리별 메뉴 표시 */}
                      {roleMenu.selectedCategories.length > 0 ? (
                        <div className="space-y-4">
                          <Label className="text-sm font-semibold block">메뉴 선택 (드래그하여 카테고리 이동)</Label>
                          {roleMenu.selectedCategories.map((categoryId) => {
                            const category = categories.find((c) => c.id === categoryId);
                            if (!category) return null;

                            const categoryMenus = menuItems.filter((m) => m.category === categoryId);
                            const IconComponent = iconMap[category.icon] || Settings;

                            return (
                              <DraggableCategorySection
                                key={categoryId}
                                category={category}
                                menuItems={categoryMenus}
                                roleMenu={roleMenu}
                                onMenuToggle={(menuId: string) => {
                                  setRoleMenus(
                                    roleMenus.map((rm) =>
                                      rm.role === roleMenu.role
                                        ? {
                                            ...rm,
                                            menuItems: rm.menuItems.includes(menuId)
                                              ? rm.menuItems.filter((id) => id !== menuId)
                                              : [...rm.menuItems, menuId],
                                          }
                                        : rm
                                    )
                                  );
                                }}
                                onMenuMove={(menuId: string, newCategoryId: string) => {
                                  // 메뉴의 카테고리 변경
                                  setMenuItems(
                                    menuItems.map((item) =>
                                      item.id === menuId
                                        ? { ...item, category: newCategoryId }
                                        : item
                                    )
                                  );
                                  toast.success("메뉴가 다른 카테고리로 이동되었습니다!");
                                }}
                              />
                            );
                          })}
                        </div>
                      ) : (
                        <div className="text-center py-12 border-2 border-dashed rounded-xl bg-gray-50">
                          <Users className="w-12 h-12 mx-auto text-gray-400 mb-3" />
                          <p className="text-gray-600">카테고리를 선택하여 시작하세요</p>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>

        {/* Add Category Dialog */}
        <Dialog open={isAddCategoryOpen} onOpenChange={setIsAddCategoryOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>새 카테고리 추가</DialogTitle>
              <DialogDescription>새로운 메뉴 카테고리를 생성합니다</DialogDescription>
            </DialogHeader>
            <div className="space-y-4 mt-4">
              <div>
                <Label>카테고리 이름</Label>
                <Input
                  value={newCategory.name}
                  onChange={(e) => setNewCategory({ ...newCategory, name: e.target.value })}
                  placeholder="예: 재고관리"
                />
              </div>
              <div>
                <Label>색상</Label>
                <div className="flex gap-2 mt-2">
                  {["#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#06B6D4", "#EC4899", "#6366F1"].map((color) => (
                    <button
                      key={color}
                      onClick={() => setNewCategory({ ...newCategory, color })}
                      className={`w-8 h-8 rounded-full border-2 ${newCategory.color === color ? "border-gray-900 ring-2 ring-gray-300" : "border-gray-300"}`}
                      style={{ backgroundColor: color }}
                    />
                  ))}
                </div>
              </div>
              <div className="flex gap-2 pt-4">
                <Button onClick={handleAddCategory} className="flex-1">
                  <Plus className="w-4 h-4 mr-2" />
                  추가
                </Button>
                <Button variant="outline" onClick={() => setIsAddCategoryOpen(false)} className="flex-1">
                  취소
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>

        {/* Add Menu Item Dialog */}
        <Dialog open={isAddMenuItemOpen} onOpenChange={setIsAddMenuItemOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>새 메뉴 항목 추가</DialogTitle>
              <DialogDescription>새로운 메뉴 항목을 생성합니다</DialogDescription>
            </DialogHeader>
            <div className="space-y-4 mt-4">
              <div>
                <Label>메뉴 이름</Label>
                <Input
                  value={newMenuItem.label}
                  onChange={(e) => setNewMenuItem({ ...newMenuItem, label: e.target.value })}
                  placeholder="예: 재고 현황"
                />
              </div>
              <div>
                <Label>카테고리</Label>
                <Select value={newMenuItem.category} onValueChange={(value) => setNewMenuItem({ ...newMenuItem, category: value })}>
                  <SelectTrigger>
                    <SelectValue placeholder="카테고리 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {categories.map((cat) => {
                      const IconComponent = iconMap[cat.icon];
                      return (
                        <SelectItem key={cat.id} value={cat.id}>
                          <div className="flex items-center gap-2">
                            <IconComponent className="w-4 h-4" style={{ color: cat.color }} />
                            {cat.name}
                          </div>
                        </SelectItem>
                      );
                    })}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>설명</Label>
                <Input
                  value={newMenuItem.description}
                  onChange={(e) => setNewMenuItem({ ...newMenuItem, description: e.target.value })}
                  placeholder="메뉴 설명"
                />
              </div>
              <div className="flex gap-2 pt-4">
                <Button onClick={handleAddMenuItem} className="flex-1">
                  <Plus className="w-4 h-4 mr-2" />
                  추가
                </Button>
                <Button variant="outline" onClick={() => setIsAddMenuItemOpen(false)} className="flex-1">
                  취소
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>

        {/* Add Attribute Dialog */}
        <Dialog open={isAttributeModalOpen} onOpenChange={setIsAttributeModalOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>새 속성 추가</DialogTitle>
              <DialogDescription>
                {menuItems.find((m) => m.id === selectedMenuItem)?.label} 메뉴의 데이터 속성을 추가합니다
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 mt-4">
              <div>
                <Label>속성 이름 *</Label>
                <Input
                  value={newAttribute.label}
                  onChange={(e) => setNewAttribute({ ...newAttribute, label: e.target.value })}
                  placeholder="예: 생산량, 불량률, 작업상태"
                />
              </div>
              <div>
                <Label>데이터 타입 *</Label>
                <Select
                  value={newAttribute.type}
                  onValueChange={(value: any) => setNewAttribute({ ...newAttribute, type: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="text">텍스트</SelectItem>
                    <SelectItem value="number">숫자</SelectItem>
                    <SelectItem value="percentage">퍼센트 (%)</SelectItem>
                    <SelectItem value="date">날짜</SelectItem>
                    <SelectItem value="select">선택 (드롭다운)</SelectItem>
                    <SelectItem value="boolean">예/아니오</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {newAttribute.type === "select" && (
                <div>
                  <Label>선택 옵션 (쉼표로 구분)</Label>
                  <Input
                    placeholder="예: 대기중, 진행중, 완료"
                    onChange={(e) =>
                      setNewAttribute({
                        ...newAttribute,
                        options: e.target.value.split(",").map((o) => o.trim()),
                      })
                    }
                  />
                </div>
              )}
              <div>
                <Label>기본값</Label>
                <Input
                  value={newAttribute.defaultValue}
                  onChange={(e) => setNewAttribute({ ...newAttribute, defaultValue: e.target.value })}
                  placeholder="기본값"
                />
              </div>
              <div className="flex items-center gap-2">
                <Checkbox
                  id="required"
                  checked={newAttribute.required}
                  onCheckedChange={(checked) =>
                    setNewAttribute({ ...newAttribute, required: checked as boolean })
                  }
                />
                <Label htmlFor="required" className="cursor-pointer">
                  필수 항목
                </Label>
              </div>
              <div className="flex gap-2 pt-4">
                <Button onClick={handleAddAttribute} className="flex-1">
                  <Plus className="w-4 h-4 mr-2" />
                  추가
                </Button>
                <Button
                  variant="outline"
                  onClick={() => {
                    setIsAttributeModalOpen(false);
                    setNewAttribute({
                      id: "",
                      label: "",
                      type: "text",
                      required: false,
                      options: [],
                      defaultValue: "",
                    });
                  }}
                  className="flex-1"
                >
                  취소
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>

        {/* Add Process Step Dialog */}
        <Dialog open={isProcessModalOpen} onOpenChange={setIsProcessModalOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>프로세스 단계 추가</DialogTitle>
              <DialogDescription>
                {menuItems.find((m) => m.id === selectedMenuForProcess)?.label} 메뉴의 프로세스 단계를 추가합니다
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 mt-4">
              <div>
                <Label>단계 이름 *</Label>
                <Input
                  value={newProcessStep.label}
                  onChange={(e) => setNewProcessStep({ ...newProcessStep, label: e.target.value })}
                  placeholder="예: 계획수립, 생산착수, 완료"
                />
              </div>
              <div>
                <Label>설명</Label>
                <Input
                  value={newProcessStep.description}
                  onChange={(e) => setNewProcessStep({ ...newProcessStep, description: e.target.value })}
                  placeholder="단계에 대한 설명"
                />
              </div>
              <div>
                <Label>색상</Label>
                <div className="flex gap-2 mt-2">
                  {["#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#06B6D4", "#EC4899", "#6366F1"].map((color) => (
                    <button
                      key={color}
                      onClick={() => setNewProcessStep({ ...newProcessStep, color })}
                      className={`w-8 h-8 rounded-full border-2 ${newProcessStep.color === color ? "border-gray-900 ring-2 ring-gray-300" : "border-gray-300"}`}
                      style={{ backgroundColor: color }}
                    />
                  ))}
                </div>
              </div>
              <div className="flex gap-2 pt-4">
                <Button onClick={handleAddProcessStep} className="flex-1">
                  <Plus className="w-4 h-4 mr-2" />
                  추가
                </Button>
                <Button
                  variant="outline"
                  onClick={() => {
                    setIsProcessModalOpen(false);
                    setNewProcessStep({
                      id: "",
                      label: "",
                      description: "",
                      color: "#3B82F6",
                      order: 1,
                    });
                  }}
                  className="flex-1"
                >
                  취소
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>
    </DndProvider>
  );
}
