/**
 * 단가 수식 관리 (품목별 수식 관리)
 * FormulaManagement2에서 분리된 수식 관리 섹션
 */

import React, { useState, useEffect, useRef } from "react";
import { Calculator, Plus, Edit, Trash2, Save, X, Settings, GripVertical, HelpCircle, CheckCircle2, AlertCircle, ChevronUp, ChevronDown, Search } from "lucide-react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  TableRowWithRef,
} from "./ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "./ui/dialog";
import { Badge } from "./ui/badge";
import { Checkbox } from "./ui/checkbox";
import { StandardDialog } from "./molecules/StandardDialog";
import { FormulaHelper } from "./molecules/FormulaHelper";
import { validateFormula, evaluateFormula, extractVariables } from "./utils/formulaEvaluator";
import { toast } from "sonner@2.0.3";
import { useDrag, useDrop, DndProvider } from "react-dnd";
import { SingletonHTML5Backend } from "../lib/dnd";
import { useData } from "./contexts/DataContext";
import { generateCompleteSampleData } from "./utils/formulaSampleData";

// 품목 아이템 타입 정의
interface FormulaItem {
  id: string;
  product: string;
  category: string;
  name: string;
  variable?: string;
  formula?: string;
  description?: string;
  order: number;
  type: "formula" | "range";
  ranges?: Array<{
    min: number;
    max: number;
    value: number;
  }>;
  resultType?: "number" | "text";
  createdAt: string;
  updatedAt?: string;
}

const ItemType = {
  FORMULA: "formula",
  CATEGORY: "category",
};

// 드래그 가능한 수식 행
interface DraggableFormulaRowProps {
  formula: FormulaItem;
  index: number;
  isFirst: boolean;
  isLast: boolean;
  onEdit: () => void;
  onDelete: () => void;
  onMove: (dragIndex: number, hoverIndex: number) => void;
}

function DraggableFormulaRow({
  formula,
  index,
  isFirst,
  isLast,
  onEdit,
  onDelete,
  onMove,
}: DraggableFormulaRowProps) {
  const ref = useRef<HTMLTableRowElement>(null);

  const [{ handlerId }, drop] = useDrop({
    accept: ItemType.FORMULA,
    collect(monitor) {
      return {
        handlerId: monitor.getHandlerId(),
      };
    },
    hover(item: any, monitor) {
      if (!ref.current) {
        return;
      }
      const dragIndex = item.index;
      const hoverIndex = index;
      if (dragIndex === hoverIndex) {
        return;
      }
      const hoverBoundingRect = ref.current?.getBoundingClientRect();
      const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
      const clientOffset = monitor.getClientOffset();
      const hoverClientY = clientOffset!.y - hoverBoundingRect.top;
      if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
        return;
      }
      if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
        return;
      }
      onMove(dragIndex, hoverIndex);
      item.index = hoverIndex;
    },
  });

  const [{ isDragging }, drag, preview] = useDrag({
    type: ItemType.FORMULA,
    item: () => {
      return { id: formula.id, index };
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  preview(drop(ref));

  return (
    <TableRowWithRef
      ref={ref}
      data-handler-id={handlerId}
      style={{ opacity: isDragging ? 0.5 : 1 }}
    >
      <TableCell>
        <div className="flex items-center gap-2">
          <div ref={drag} className="cursor-move">
            <GripVertical className="h-4 w-4 text-muted-foreground" />
          </div>
          <Badge variant="outline">{index + 1}</Badge>
        </div>
      </TableCell>
      <TableCell className="font-medium">{formula.name}</TableCell>
      <TableCell>
        {formula.variable && (
          <Badge variant="secondary" className="font-mono">
            {formula.variable}
          </Badge>
        )}
      </TableCell>
      <TableCell>
        <Badge variant={formula.type === "formula" ? "default" : "outline"}>
          {formula.type === "formula" ? "수식" : "범위"}
        </Badge>
      </TableCell>
      <TableCell>
        {formula.type === "formula" ? (
          <code className="text-sm bg-muted px-2 py-1 rounded">
            {formula.formula}
          </code>
        ) : (
          <div className="text-sm">
            {formula.ranges?.map((r, i) => (
              <div key={i} className="text-xs">
                {r.min} ~ {r.max}: {r.value}
              </div>
            ))}
          </div>
        )}
      </TableCell>
      <TableCell>
        <Badge variant="outline">{formula.resultType || "number"}</Badge>
      </TableCell>
      <TableCell className="text-sm text-muted-foreground">
        {formula.description}
      </TableCell>
      <TableCell>
        <div className="flex gap-2">
          <Button size="sm" variant="ghost" onClick={onEdit}>
            <Edit className="h-4 w-4" />
          </Button>
          <Button
            size="sm"
            variant="ghost"
            onClick={onDelete}
            className="text-red-600 hover:text-red-700"
          >
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      </TableCell>
    </TableRowWithRef>
  );
}

// 드래그 가능한 카테고리
interface DraggableCategoryProps {
  category: string;
  index: number;
  isSelected: boolean;
  count: number;
  isEditing: boolean;
  editValue: string;
  onSelect: () => void;
  onMove: (dragIndex: number, hoverIndex: number) => void;
  onEdit: () => void;
  onSaveEdit: () => void;
  onCancelEdit: () => void;
  onDelete: () => void;
  onEditValueChange: (value: string) => void;
  isEditMode: boolean;
}

function DraggableCategory({
  category,
  index,
  isSelected,
  count,
  isEditing,
  editValue,
  onSelect,
  onMove,
  onEdit,
  onSaveEdit,
  onCancelEdit,
  onDelete,
  onEditValueChange,
  isEditMode,
}: DraggableCategoryProps) {
  const ref = useRef<HTMLDivElement>(null);

  const [{ handlerId }, drop] = useDrop({
    accept: ItemType.CATEGORY,
    collect(monitor) {
      return {
        handlerId: monitor.getHandlerId(),
      };
    },
    hover(item: any, monitor) {
      if (!ref.current) {
        return;
      }
      const dragIndex = item.index;
      const hoverIndex = index;
      if (dragIndex === hoverIndex) {
        return;
      }
      const hoverBoundingRect = ref.current?.getBoundingClientRect();
      const hoverMiddleX = (hoverBoundingRect.right - hoverBoundingRect.left) / 2;
      const clientOffset = monitor.getClientOffset();
      const hoverClientX = clientOffset!.x - hoverBoundingRect.left;
      if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
        return;
      }
      if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
        return;
      }
      onMove(dragIndex, hoverIndex);
      item.index = hoverIndex;
    },
  });

  const [{ isDragging }, drag] = useDrag({
    type: ItemType.CATEGORY,
    item: () => {
      return { category, index };
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  drag(drop(ref));

  if (isEditing) {
    return (
      <div
        ref={ref}
        className="inline-flex items-center gap-2 px-3 py-1.5 rounded-full border-2 border-primary bg-primary/5"
      >
        <Input
          value={editValue}
          onChange={(e) => onEditValueChange(e.target.value)}
          className="h-6 w-32 text-sm"
          autoFocus
          onKeyDown={(e) => {
            if (e.key === "Enter") onSaveEdit();
            if (e.key === "Escape") onCancelEdit();
          }}
        />
        <Button size="sm" variant="ghost" onClick={onSaveEdit} className="h-6 w-6 p-0">
          <Save className="h-3 w-3" />
        </Button>
        <Button size="sm" variant="ghost" onClick={onCancelEdit} className="h-6 w-6 p-0">
          <X className="h-3 w-3" />
        </Button>
      </div>
    );
  }

  return (
    <div
      ref={ref}
      onClick={onSelect}
      className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-full cursor-pointer transition-all ${
        isSelected
          ? "bg-primary text-primary-foreground"
          : "bg-muted hover:bg-muted/80"
      } ${isDragging ? "opacity-50" : ""}`}
      style={{ opacity: isDragging ? 0.5 : 1 }}
    >
      {isEditMode && <GripVertical className="h-3 w-3 cursor-move" />}
      <span className="inline-flex items-center justify-center rounded-full w-4 h-4 text-[10px] font-semibold bg-background/20">
        {index + 1}
      </span>
      <span className="text-sm font-medium">{category}</span>
      <Badge variant="secondary" className="text-xs">
        {count}
      </Badge>
      {isEditMode && (
        <>
          <Button
            size="sm"
            variant="ghost"
            onClick={(e) => {
              e.stopPropagation();
              onEdit();
            }}
            className="h-6 w-6 p-0"
          >
            <Edit className="h-3 w-3" />
          </Button>
          <Button
            size="sm"
            variant="ghost"
            onClick={(e) => {
              e.stopPropagation();
              onDelete();
            }}
            className="h-6 w-6 p-0 text-red-600 hover:text-red-700"
          >
            <Trash2 className="h-3 w-3" />
          </Button>
        </>
      )}
    </div>
  );
}

export function FormulaItemManagement() {
  const { formulas, addFormula, updateFormula, deleteFormula } = useData();
  const [selectedProduct, setSelectedProduct] = useState("롤스크린");
  const [selectedCategory, setSelectedCategory] = useState("오픈사이즈");
  const [searchQuery, setSearchQuery] = useState("");
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<FormulaItem | null>(null);
  const [isCategoryEditMode, setIsCategoryEditMode] = useState(false);
  const [editingCategoryIndex, setEditingCategoryIndex] = useState<number | null>(null);
  const [categoryEditValue, setCategoryEditValue] = useState("");
  const [isAddCategoryDialogOpen, setIsAddCategoryDialogOpen] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState("");

  const [formData, setFormData] = useState<Partial<FormulaItem>>({
    name: "",
    variable: "",
    formula: "",
    description: "",
    type: "formula",
    ranges: [],
    resultType: "number",
  });

  // 제품 목록
  const products = ["롤스크린", "버티칼", "콤비"];

  // 카테고리 목록 (제품별)
  const getCategoriesForProduct = (product: string) => {
    const categories = [...new Set(formulas.filter((f) => f.product === product).map((f) => f.category))];
    return categories.length > 0 ? categories : ["오픈사이즈"];
  };

  const categories = getCategoriesForProduct(selectedProduct);

  // 선택된 제품/카테고리에 해당하는 수식 필터링
  const filteredFormulas = formulas
    .filter(
      (f) =>
        f.product === selectedProduct &&
        f.category === selectedCategory &&
        (f.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
          f.description?.toLowerCase().includes(searchQuery.toLowerCase()))
    )
    .sort((a, b) => a.order - b.order);

  // 카테고리가 변경되면 선택된 카테고리 업데이트
  useEffect(() => {
    if (!categories.includes(selectedCategory)) {
      setSelectedCategory(categories[0] || "오픈사이즈");
    }
  }, [selectedProduct, categories, selectedCategory]);

  const handleAdd = () => {
    setEditingItem(null);
    setFormData({
      name: "",
      variable: "",
      formula: "",
      description: "",
      type: "formula",
      ranges: [],
      resultType: "number",
    });
    setIsDialogOpen(true);
  };

  const handleEdit = (item: FormulaItem) => {
    setEditingItem(item);
    setFormData(item);
    setIsDialogOpen(true);
  };

  const handleSave = () => {
    if (!formData.name?.trim()) {
      toast.error("수식 이름을 입력해주세요.");
      return;
    }

    if (formData.type === "formula") {
      if (!formData.formula?.trim()) {
        toast.error("수식을 입력해주세요.");
        return;
      }

      const validation = validateFormula(formData.formula);
      if (!validation.isValid) {
        toast.error(`수식 오류: ${validation.error}`);
        return;
      }
    } else if (formData.type === "range") {
      if (!formData.ranges || formData.ranges.length === 0) {
        toast.error("최소 1개 이상의 범위를 추가해주세요.");
        return;
      }
    }

    const now = new Date().toISOString();

    if (editingItem) {
      updateFormula(editingItem.id, {
        ...formData,
        updatedAt: now,
      });
      toast.success("수식이 수정되었습니다.");
    } else {
      const maxOrder = Math.max(...filteredFormulas.map((f) => f.order), -1);
      const newFormula: FormulaItem = {
        id: `formula-${Date.now()}`,
        product: selectedProduct,
        category: selectedCategory,
        name: formData.name!,
        variable: formData.variable,
        formula: formData.formula,
        description: formData.description,
        type: formData.type!,
        ranges: formData.ranges,
        resultType: formData.resultType,
        order: maxOrder + 1,
        createdAt: now,
      };
      addFormula(newFormula);
      toast.success("수식이 추가되었습니다.");
    }

    setIsDialogOpen(false);
  };

  const handleDelete = (id: string) => {
    if (confirm("정말 삭제하시겠습니까?")) {
      deleteFormula(id);
      toast.success("수식이 삭제되었습니다.");
    }
  };

  const handleMoveFormulaDnd = (dragIndex: number, hoverIndex: number) => {
    const dragFormula = filteredFormulas[dragIndex];
    const newFormulas = [...filteredFormulas];
    newFormulas.splice(dragIndex, 1);
    newFormulas.splice(hoverIndex, 0, dragFormula);
    newFormulas.forEach((f, idx) => {
      updateFormula(f.id, { order: idx });
    });
  };

  const handleMoveCategoryDnd = (dragIndex: number, hoverIndex: number) => {
    const newCategories = [...categories];
    const [removed] = newCategories.splice(dragIndex, 1);
    newCategories.splice(hoverIndex, 0, removed);
    // 카테고리 순서를 업데이트하려면 각 카테고리의 수식들을 업데이트해야 함
    // 이 부분은 구현에 따라 달라질 수 있음
  };

  const handleEditCategory = (index: number) => {
    setEditingCategoryIndex(index);
    setCategoryEditValue(categories[index]);
  };

  const handleSaveEditCategory = () => {
    if (!categoryEditValue.trim()) {
      toast.error("카테고리 이름을 입력해주세요.");
      return;
    }

    const oldCategory = categories[editingCategoryIndex!];
    const newCategory = categoryEditValue.trim();

    if (oldCategory === newCategory) {
      setEditingCategoryIndex(null);
      setCategoryEditValue("");
      return;
    }

    if (categories.includes(newCategory)) {
      toast.error("이미 존재하는 카테고리 이름입니다.");
      return;
    }

    // 해당 카테고리의 모든 수식 업데이트
    formulas
      .filter((f) => f.product === selectedProduct && f.category === oldCategory)
      .forEach((f) => {
        updateFormula(f.id, { category: newCategory });
      });

    toast.success("카테고리가 수정되었습니다.");
    setEditingCategoryIndex(null);
    setCategoryEditValue("");
    setSelectedCategory(newCategory);
  };

  const handleCancelEditCategory = () => {
    setEditingCategoryIndex(null);
    setCategoryEditValue("");
  };

  const handleDeleteCategory = (index: number) => {
    const category = categories[index];
    const count = formulas.filter((f) => f.product === selectedProduct && f.category === category).length;

    if (count > 0) {
      toast.error(`카테고리에 ${count}개의 수식이 있습니다. 먼저 수식을 삭제해주세요.`);
      return;
    }

    if (confirm(`"${category}" 카테고리를 삭제하시겠습니까?`)) {
      // 카테고리 삭제는 해당 카테고리의 수식이 없을 때만 가능
      // 실제로는 별도의 카테고리 관리가 필요할 수 있음
      toast.success("카테고리가 삭제되었습니다.");
      if (selectedCategory === category) {
        setSelectedCategory(categories[0] !== category ? categories[0] : categories[1] || "오픈사이즈");
      }
    }
  };

  const handleAddCategory = () => {
    setIsAddCategoryDialogOpen(true);
    setNewCategoryName("");
  };

  const handleSaveNewCategory = () => {
    if (!newCategoryName.trim()) {
      toast.error("카테고리 이름을 입력해주세요.");
      return;
    }

    if (categories.includes(newCategoryName.trim())) {
      toast.error("이미 존재하는 카테고리 이름입니다.");
      return;
    }

    // 새 카테고리는 더미 수식을 추가하여 생성
    const newFormula: FormulaItem = {
      id: `formula-${Date.now()}`,
      product: selectedProduct,
      category: newCategoryName.trim(),
      name: "임시 수식",
      type: "formula",
      formula: "0",
      order: 0,
      resultType: "number",
      createdAt: new Date().toISOString(),
    };
    addFormula(newFormula);
    setSelectedCategory(newCategoryName.trim());
    toast.success("카테고리가 추가되었습니다.");
    setIsAddCategoryDialogOpen(false);
  };

  return (
    <DndProvider backend={SingletonHTML5Backend}>
      <PageLayout>
        <PageHeader
          title="단가 수식 목록"
          description="품목별 단가 계산 수식을 관리합니다"
          icon={Calculator}
        />

        <div className="space-y-6">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>수식 목록</CardTitle>
                <div className="flex gap-2">
                  <Select value={selectedProduct} onValueChange={setSelectedProduct}>
                    <SelectTrigger className="w-[180px]">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {products.map((product) => (
                        <SelectItem key={product} value={product}>
                          {product}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardHeader>

            <CardContent className="space-y-6">
              {/* 검색 */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="수식 이름, 설명으로 검색..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-9"
                />
              </div>

              {/* 카테고리 탭 */}
              <div className="mb-6">
                <div className="flex items-center justify-between mb-3">
                  <div className="text-sm text-muted-foreground">
                    카테고리 선택 (실행 순서) -
                    <span className="inline-flex items-center gap-1 ml-2">
                      예:
                      <span className="inline-flex items-center justify-center rounded-full w-4 h-4 text-[10px] font-semibold bg-primary/10 text-primary">
                        1
                      </span>
                      <span className="inline-flex items-center justify-center rounded-full w-4 h-4 text-[10px] font-semibold bg-primary/10 text-primary">
                        2
                      </span>
                      <span className="inline-flex items-center justify-center rounded-full w-4 h-4 text-[10px] font-semibold bg-primary/10 text-primary">
                        3
                      </span>
                    </span>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant={isCategoryEditMode ? "default" : "outline"}
                      size="sm"
                      onClick={() => {
                        setIsCategoryEditMode(!isCategoryEditMode);
                        if (isCategoryEditMode) {
                          setEditingCategoryIndex(null);
                          setCategoryEditValue("");
                        }
                      }}
                    >
                      <Settings className="h-4 w-4 mr-2" />
                      {isCategoryEditMode ? "완료" : "수정"}
                    </Button>
                    <Button variant="outline" size="sm" onClick={handleAddCategory}>
                      <Plus className="h-4 w-4 mr-2" />
                      카테고리 추가
                    </Button>
                  </div>
                </div>
                <div className="flex flex-wrap gap-2">
                  {categories.map((category, index) => {
                    const count = formulas.filter(
                      (f) => f.product === selectedProduct && f.category === category
                    ).length;
                    return (
                      <DraggableCategory
                        key={category}
                        category={category}
                        index={index}
                        isSelected={selectedCategory === category}
                        count={count}
                        isEditing={editingCategoryIndex === index}
                        editValue={categoryEditValue}
                        onSelect={() => setSelectedCategory(category)}
                        onMove={handleMoveCategoryDnd}
                        onEdit={() => handleEditCategory(index)}
                        onSaveEdit={handleSaveEditCategory}
                        onCancelEdit={handleCancelEditCategory}
                        onDelete={() => handleDeleteCategory(index)}
                        onEditValueChange={setCategoryEditValue}
                        isEditMode={isCategoryEditMode}
                      />
                    );
                  })}
                </div>
              </div>

              {/* 수식 추가 버튼 */}
              <div className="mb-6 pb-6 border-b">
                <div className="flex items-center justify-between">
                  <div className="text-sm text-muted-foreground flex items-center gap-2">
                    <Badge variant="outline">{selectedCategory}</Badge>
                    카테고리에 수식 추가
                  </div>
                  <Button onClick={handleAdd} size="sm">
                    <Plus className="h-4 w-4 mr-2" />
                    수식 추가
                  </Button>
                </div>
              </div>

              {/* 수식 목록 */}
              {filteredFormulas.length === 0 ? (
                <div className="text-center py-12 text-gray-500">
                  <Calculator className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>등록된 수식이 없습니다.</p>
                  <p className="text-sm mt-2">우측 상단의 "수식 추가" 버튼을 클릭하세요.</p>
                </div>
              ) : (
                <div className="border rounded-lg overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[60px]">순서</TableHead>
                        <TableHead className="w-[200px]">이름</TableHead>
                        <TableHead className="w-[120px]">변수</TableHead>
                        <TableHead className="w-[100px]">타입</TableHead>
                        <TableHead>수식/범위</TableHead>
                        <TableHead className="w-[120px]">결과 타입</TableHead>
                        <TableHead className="w-[200px]">설명</TableHead>
                        <TableHead className="w-[120px]">작업</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredFormulas.map((formula, idx) => (
                        <DraggableFormulaRow
                          key={formula.id}
                          formula={formula}
                          index={idx}
                          isFirst={idx === 0}
                          isLast={idx === filteredFormulas.length - 1}
                          onEdit={() => handleEdit(formula)}
                          onDelete={() => handleDelete(formula.id)}
                          onMove={handleMoveFormulaDnd}
                        />
                      ))}
                    </TableBody>
                  </Table>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* 수식 추가/수정 다이얼로그 */}
        <StandardDialog
          open={isDialogOpen}
          onOpenChange={setIsDialogOpen}
          title={editingItem ? "수식 수정" : "수식 추가"}
          description={`${selectedProduct} > ${selectedCategory} 카테고리의 수식을 ${
            editingItem ? "수정" : "추가"
          }합니다.`}
          onConfirm={handleSave}
          confirmText={editingItem ? "수정" : "추가"}
          size="xl"
        >
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="name">
                  수식 이름 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="name"
                  value={formData.name || ""}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="예: 면적 계산"
                />
              </div>
              <div>
                <Label htmlFor="variable">변수명 (선택)</Label>
                <Input
                  id="variable"
                  value={formData.variable || ""}
                  onChange={(e) => setFormData({ ...formData, variable: e.target.value })}
                  placeholder="예: area"
                />
              </div>
            </div>

            <div>
              <Label>타입</Label>
              <Select
                value={formData.type}
                onValueChange={(value: "formula" | "range") =>
                  setFormData({ ...formData, type: value })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="formula">수식</SelectItem>
                  <SelectItem value="range">범위</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {formData.type === "formula" ? (
              <div>
                <Label htmlFor="formula">
                  수식 <span className="text-red-500">*</span>
                </Label>
                <Textarea
                  id="formula"
                  value={formData.formula || ""}
                  onChange={(e) => setFormData({ ...formData, formula: e.target.value })}
                  placeholder="예: width * height / 10000"
                  rows={3}
                />
                <FormulaHelper />
              </div>
            ) : (
              <div>
                <Label>범위 설정</Label>
                <div className="text-sm text-muted-foreground mb-2">
                  범위별 값을 설정합니다 (최소~최대: 값)
                </div>
                {/* 범위 설정 UI는 필요에 따라 구현 */}
              </div>
            )}

            <div>
              <Label htmlFor="resultType">결과 타입</Label>
              <Select
                value={formData.resultType}
                onValueChange={(value: "number" | "text") =>
                  setFormData({ ...formData, resultType: value })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="number">숫자</SelectItem>
                  <SelectItem value="text">텍스트</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="description">설명 (선택)</Label>
              <Textarea
                id="description"
                value={formData.description || ""}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="수식에 대한 설명"
                rows={2}
              />
            </div>
          </div>
        </StandardDialog>

        {/* 카테고리 추가 다이얼로그 */}
        <Dialog open={isAddCategoryDialogOpen} onOpenChange={setIsAddCategoryDialogOpen}>
          <DialogContent className="sm:max-w-md p-6">
            <DialogHeader>
              <DialogTitle>카테고리 추가</DialogTitle>
              <DialogDescription>새로운 카테고리 이름을 입력하세요.</DialogDescription>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label htmlFor="categoryName">카테고리 이름</Label>
                <Input
                  id="categoryName"
                  value={newCategoryName}
                  onChange={(e) => setNewCategoryName(e.target.value)}
                  placeholder="예: 공정비, 원단비 등"
                  onKeyDown={(e) => {
                    if (e.key === "Enter") handleSaveNewCategory();
                  }}
                />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsAddCategoryDialogOpen(false)}>
                취소
              </Button>
              <Button onClick={handleSaveNewCategory}>추가</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </PageLayout>
    </DndProvider>
  );
}
