/**
 * 품목 단가 맵핑 관리
 * 분류 그룹별 또는 개별 품목에 단가 수식을 할당
 */

import { useState, useMemo } from "react";
import { Plus, Edit, Trash2, Search, HelpCircle, AlertCircle, X } from "lucide-react";
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 { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "./ui/dialog";
import { Checkbox } from "./ui/checkbox";
import { toast } from "sonner@2.0.3";
import { useData } from "./contexts/DataContext";
import { FormulaHelper } from "./molecules/FormulaHelper";
import { validateFormula, extractVariables } from "./utils/formulaEvaluator";

interface PriceMappingItem {
  id: string;
  mappingType: 'individual' | 'categoryGroup'; // 개별 품목 | 분류 그룹별
  
  // 개별 품목
  itemCode?: string;
  itemName?: string;
  basePrice?: number;
  quantityFormula?: string;
  
  // 분류 그룹별 (categoryGroup)
  categoryGroupId?: string; // 분류 그룹 ID
  categoryGroupName?: string; // 분류 그룹명 (표시용)
  
  // 공통
  priceFormulaId: string; // 적용할 단가 계산 수식 ID
  priceFormulaName: string; // 단가 수식명 (표시용)
  description?: string;
  enabled: boolean;
  priority?: number;
  createdAt: string;
  updatedAt?: string;
}

interface Formula {
  id: string;
  name: string;
  category: string;
  formula: string;
}

interface ItemPriceMappingManagerProps {
  formulas: Formula[];
  mappings: PriceMappingItem[];
  onMappingsChange: (mappings: PriceMappingItem[]) => void;
}

export function ItemPriceMappingManager({ formulas, mappings, onMappingsChange }: ItemPriceMappingManagerProps) {
  const { itemMasters, categoryGroups } = useData();
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingMapping, setEditingMapping] = useState<PriceMappingItem | null>(null);
  const [activeTab, setActiveTab] = useState<'categoryGroup' | 'individual'>('categoryGroup');
  const [searchQuery, setSearchQuery] = useState("");
  
  // 변수 검색 및 함수 도움말 상태
  const [showVariablePicker, setShowVariablePicker] = useState(false);
  const [variableSearchQuery, setVariableSearchQuery] = useState("");
  const [showFormulaHelper, setShowFormulaHelper] = useState(false);
  const [priceFormula, setPriceFormula] = useState("");
  const [formulaValidation, setFormulaValidation] = useState({ valid: true, error: "" });

  // 단가 계산 수식만 필터링 (단가계산 카테고리 또는 곱셈/나눗셈이 포함된 수식)
  const priceFormulas = useMemo(() => {
    return formulas.filter(f => 
      f.category === '단가계산' || 
      (f.name && f.name.includes('단가')) ||
      (f.name && f.name.includes('가격')) ||
      (f.formula && (f.formula.includes('*') || f.formula.includes('/')))
    );
  }, [formulas]);

  // 초기 폼 데이터
  const getEmptyForm = (): Partial<PriceMappingItem> => ({
    mappingType: activeTab,
    enabled: true,
    quantityFormula: '1',
    priority: mappings.length
  });

  const [formData, setFormData] = useState<Partial<PriceMappingItem>>(getEmptyForm());

  // 추가/수정 다이얼로그 열기
  const handleAdd = () => {
    setEditingMapping(null);
    setFormData(getEmptyForm());
    setPriceFormula('');
    setFormulaValidation({ valid: true, error: '' });
    setShowVariablePicker(false);
    setShowFormulaHelper(false);
    setIsDialogOpen(true);
  };

  const handleEdit = (mapping: PriceMappingItem) => {
    setEditingMapping(mapping);
    setFormData(mapping);
    setActiveTab(mapping.mappingType);
    // 기존 수식 불러오기
    const existingFormula = formulas.find(f => f.id === mapping.priceFormulaId);
    if (existingFormula) {
      setPriceFormula(existingFormula.formula);
      setFormulaValidation({ valid: true, error: '' });
    } else {
      setPriceFormula('');
      setFormulaValidation({ valid: true, error: '' });
    }
    setShowVariablePicker(false);
    setShowFormulaHelper(false);
    setIsDialogOpen(true);
  };

  // 저장
  const handleSave = () => {
    // 유효성 검사 - 단가 계산 수식 (필수)
    if (!priceFormula || priceFormula.trim() === '') {
      toast.error('단가 계산 수식을 입력해주세요.');
      return;
    }

    if (!formulaValidation.valid) {
      toast.error('단가 계산 수식이 유효하지 않습니다. 수식을 확인해주세요.');
      return;
    }

    if (formData.mappingType === 'individual') {
      if (!formData.itemCode) {
        toast.error('품목을 선택해주세요.');
        return;
      }
    } else if (formData.mappingType === 'categoryGroup') {
      if (!formData.categoryGroupId) {
        toast.error('분류 그룹을 선택해주세요.');
        return;
      }
    }

    // 입력한 수식을 formulas에 임시 저장하거나, priceFormulaId로 저장
    // 새로운 수식인 경우 formulas 배열에 추가
    const now = new Date().toISOString();
    let selectedFormulaId = formData.priceFormulaId;
    let selectedFormulaName = '';

    // 기존 수식 중에 동일한 수식이 있는지 확인
    const existingFormula = formulas.find(f => f.formula === priceFormula);
    
    if (existingFormula) {
      selectedFormulaId = existingFormula.id;
      selectedFormulaName = existingFormula.name;
    } else {
      // 새로운 수식인 경우 ID 생성
      selectedFormulaId = `formula-${Date.now()}`;
      selectedFormulaName = `단가수식_${Date.now()}`;
      
      // 부모 컴포넌트에 새 수식 추가 알림이 필요할 수 있음
      // 여기서는 임시로 ID만 저장
    }

    if (editingMapping) {
      // 수정
      const updated = mappings.map(m =>
        m.id === editingMapping.id
          ? { 
              ...formData, 
              id: m.id, 
              priceFormulaId: selectedFormulaId,
              priceFormulaName: selectedFormulaName,
              quantityFormula: priceFormula, // 수식 저장
              updatedAt: now 
            } as PriceMappingItem
          : m
      );
      onMappingsChange(updated);
      toast.success('단가 맵핑이 수정되었습니다.');
    } else {
      // 추가
      const newMapping: PriceMappingItem = {
        ...formData,
        id: `mapping-${Date.now()}`,
        priceFormulaId: selectedFormulaId,
        priceFormulaName: selectedFormulaName,
        quantityFormula: priceFormula, // 수식 저장
        createdAt: now,
        priority: formData.mappingType === 'individual' ? 0 : 100 + mappings.length
      } as PriceMappingItem;
      
      onMappingsChange([...mappings, newMapping]);
      toast.success('단가 맵핑이 추가되었습니다.');
    }

    setIsDialogOpen(false);
    setFormData(getEmptyForm());
    setPriceFormula('');
    setFormulaValidation({ valid: true, error: '' });
  };

  // 삭제
  const handleDelete = (id: string) => {
    if (confirm('이 맵핑을 삭제하시겠습니까?')) {
      onMappingsChange(mappings.filter(m => m.id !== id));
      toast.success('단가 맵핑이 삭제되었습니다.');
    }
  };

  // 활성화 토글
  const toggleEnabled = (id: string) => {
    onMappingsChange(
      mappings.map(m => m.id === id ? { ...m, enabled: !m.enabled } : m)
    );
  };

  // 품목 선택
  const handleSelectItem = (itemCode: string) => {
    const item = itemMasters.find(i => i.itemCode === itemCode);
    if (item) {
      setFormData(prev => ({
        ...prev,
        itemCode: item.itemCode,
        itemName: item.itemName,
        basePrice: item.sellingPrice || 0
      }));
    }
  };

  // 분류 그룹 선택
  const handleSelectCategoryGroup = (groupId: string) => {
    const group = categoryGroups.find(g => g.id === groupId);
    if (group) {
      setFormData(prev => ({
        ...prev,
        categoryGroupId: group.id,
        categoryGroupName: group.name
      }));
    }
  };

  // 분류별/개별 맵핑 분리
  const categoryMappings = mappings.filter(m => m.mappingType === 'categoryGroup');
  const individualMappings = mappings.filter(m => m.mappingType === 'individual');

  // 매핑된 품목 개수 계산
  const getMappedItemCount = (mapping: PriceMappingItem): number => {
    if (mapping.mappingType === 'individual') {
      return 1;
    }
    
    if (mapping.mappingType === 'categoryGroup' && mapping.categoryGroupId) {
      const group = categoryGroups.find(g => g.id === mapping.categoryGroupId);
      if (!group) return 0;
      
      // 그룹에 포함된 카테고리들의 품목 개수 합산
      return itemMasters.filter(item => {
        // 품목의 어떤 필드가 그룹의 카테고리와 일치하는지 확인
        return group.categories.some(category => {
          // 품목의 모든 필드를 순회하면서 카테고리와 일치하는지 확인
          return Object.values(item).some(value => value === category);
        });
      }).length;
    }
    
    return 0;
  };

  // 검색 필터
  const filteredMappings = useMemo(() => {
    if (!searchQuery) return mappings;
    
    const query = searchQuery.toLowerCase();
    return mappings.filter(m => 
      m.priceFormulaName?.toLowerCase().includes(query) ||
      m.itemName?.toLowerCase().includes(query) ||
      m.itemCode?.toLowerCase().includes(query) ||
      m.categoryGroupName?.toLowerCase().includes(query) ||
      m.description?.toLowerCase().includes(query)
    );
  }, [mappings, searchQuery]);

  // 등록된 변수 목록 가져오기 (품목 수식 관리에서 정의한 변수들)
  const availableVariables = useMemo(() => {
    const variableMap = new Map<string, { variable: string; name: string; category: string }>();
    
    // 각 수식에서 변수 추출
    formulas.forEach(f => {
      const variables = extractVariables(f.formula);
      variables.forEach(varName => {
        // 시스템 변수 제외 (UP는 시스템 변수로 별도 표시)
        if (varName === 'UP') return;
        
        // 변수가 아직 맵에 없으면 추가
        if (!variableMap.has(varName)) {
          variableMap.set(varName, {
            variable: varName,
            name: f.name, // 해당 변수를 사용하는 수식명을 이름으로
            category: f.category
          });
        }
      });
    });
    
    return Array.from(variableMap.values());
  }, [formulas]);
  
  // 변수 검색 필터링
  const filteredVariables = useMemo(() => {
    if (!variableSearchQuery) return availableVariables;
    const query = variableSearchQuery.toLowerCase();
    return availableVariables.filter(v =>
      v.variable.toLowerCase().includes(query) ||
      v.name.toLowerCase().includes(query)
    );
  }, [availableVariables, variableSearchQuery]);
  
  // 변수 삽입 핸들러
  const handleInsertVariable = (variable: string) => {
    const input = document.getElementById("priceFormula") as HTMLInputElement;
    if (input) {
      const cursorPos = input.selectionStart || priceFormula.length;
      const before = priceFormula.substring(0, cursorPos);
      const after = priceFormula.substring(cursorPos);
      const newFormula = before + variable + after;
      setPriceFormula(newFormula);
      
      setTimeout(() => {
        const validation = validateFormula(newFormula);
        setFormulaValidation(validation);
      }, 0);
    }
    setShowVariablePicker(false);
    setVariableSearchQuery("");
  };

  // 매핑 카드 렌더링
  const renderMappingCard = (mapping: PriceMappingItem) => {
    const itemCount = getMappedItemCount(mapping);
    const isGroup = mapping.mappingType === 'categoryGroup';
    const group = isGroup ? categoryGroups.find(g => g.id === mapping.categoryGroupId) : null;

    return (
      <div
        key={mapping.id}
        className={`border rounded-lg p-4 transition-all ${
          mapping.enabled 
            ? 'bg-white border-blue-200 shadow-sm hover:shadow-md' 
            : 'bg-gray-50 border-gray-200 opacity-60'
        }`}
      >
        <div className="flex items-start gap-3">
          {/* 체크박스 */}
          <div className="pt-1">
            <Checkbox
              checked={mapping.enabled}
              onCheckedChange={() => toggleEnabled(mapping.id)}
            />
          </div>

          {/* 내용 */}
          <div className="flex-1 space-y-3">
            {/* 헤더 */}
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <div className="font-semibold">
                    {isGroup ? mapping.categoryGroupName : mapping.itemName}
                  </div>
                  <Badge variant={isGroup ? "secondary" : "default"}>
                    {isGroup ? '그룹' : '개별'}
                  </Badge>
                </div>
                <div className="text-xs text-muted-foreground">
                  {isGroup ? `${itemCount}개 품목` : mapping.itemCode}
                </div>
              </div>
              <div className="flex gap-1 ml-2">
                <Button size="sm" variant="ghost" onClick={() => handleEdit(mapping)} className="h-8 w-8 p-0">
                  <Edit className="h-3 w-3" />
                </Button>
                <Button 
                  size="sm" 
                  variant="ghost" 
                  onClick={() => handleDelete(mapping.id)}
                  className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
                >
                  <Trash2 className="h-3 w-3" />
                </Button>
              </div>
            </div>

            {/* 그룹 카테고리 표시 */}
            {isGroup && group && (
              <div className="flex flex-wrap gap-1">
                {group.categories.map(cat => (
                  <Badge key={cat} variant="outline" className="text-xs px-2 py-0">
                    {cat}
                  </Badge>
                ))}
              </div>
            )}

            {/* 수식 정보 */}
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-sm">
                <span className="text-muted-foreground">적용 수식:</span>
                <Badge variant="outline" className="font-mono">
                  {mapping.priceFormulaName}
                </Badge>
              </div>
              <div className="flex items-center gap-2 text-sm">
                <span className="text-muted-foreground">수량 계산:</span>
                <code className="px-2 py-1 bg-muted rounded text-xs font-mono">
                  {mapping.quantityFormula}
                </code>
              </div>
              {mapping.basePrice && (
                <div className="flex items-center gap-2 text-sm">
                  <span className="text-muted-foreground">기준 단가:</span>
                  <span className="font-semibold text-blue-600">
                    {mapping.basePrice.toLocaleString()}원
                  </span>
                </div>
              )}
              {mapping.description && (
                <div className="text-xs text-muted-foreground">
                  {mapping.description}
                </div>
              )}
            </div>


          </div>
        </div>
      </div>
    );
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>단가 수식 관리</CardTitle>
            <p className="text-sm text-muted-foreground mt-1">
              분류 그룹 또는 개별 품목에 단가 계산 수식을 연결합니다
            </p>
          </div>
          <Button onClick={handleAdd} size="sm">
            단가 수식 추가
          </Button>
        </div>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* 검색 */}
        <div>
          <Input
            placeholder="수식명, 품목명, 그룹명으로 검색..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>

        {/* 맵핑 목록 */}
        {filteredMappings.length === 0 ? (
          <Card>
            <CardContent className="p-12">
              <div className="text-center">
                <p className="text-muted-foreground mb-4">
                  {searchQuery ? '검색 결과가 없습니다' : '등록된 단가 수식 연결이 없습니다'}
                </p>
                {!searchQuery && (
                  <Button variant="outline" onClick={handleAdd}>
                    첫 단가 수식 연결 추가하기
                  </Button>
                )}
              </div>
            </CardContent>
          </Card>
        ) : (
          <Card>
            <CardContent className="p-6">
              <div className="space-y-3">
                {filteredMappings.length === 0 ? (
                  <div className="text-center py-12 text-muted-foreground border-2 border-dashed rounded-lg">
                    단가 수식 연결이 없습니다
                  </div>
                ) : (
                  filteredMappings.map(renderMappingCard)
                )}
              </div>
            </CardContent>
          </Card>
        )}
      </CardContent>

      {/* 추가/수정 다이얼로그 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto p-6">
          <DialogHeader>
            <DialogTitle>
              {editingMapping ? '단가 수식 연결 수정' : '단가 수식 연결'}
            </DialogTitle>
            <DialogDescription>
              분류 그룹 또는 품목에 적용할 단가 계산 수식을 연결합니다
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 px-6">
            {/* 그룹별 선택 */}
            {formData.mappingType === 'categoryGroup' && (
              <>
                <div>
                  <Label>분류 그룹</Label>
                  <Select
                    value={formData.categoryGroupId}
                    onValueChange={handleSelectCategoryGroup}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="분류 그룹 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {categoryGroups.length === 0 ? (
                        <div className="p-4 text-sm text-muted-foreground text-center">
                          등록된 그룹이 없습니다<br/>
                          먼저 분류 그룹을 생성해주세요
                        </div>
                      ) : (
                        categoryGroups.map(group => (
                          <SelectItem key={group.id} value={group.id}>
                            <div>
                              <div className="font-medium">{group.name}</div>
                              <div className="text-xs text-muted-foreground">
                                {group.categories?.join(', ') || '카테고리 없음'}
                              </div>
                            </div>
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {formData.categoryGroupId && (() => {
                  const group = categoryGroups.find(g => g.id === formData.categoryGroupId);
                  const itemCount = getMappedItemCount({ ...formData } as PriceMappingItem);
                  return (
                    <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm">
                      <div className="font-medium text-blue-900 mb-2">
                        선택한 그룹: {group?.name}
                      </div>
                      <div className="text-blue-700 space-y-1 text-xs">
                        <div>포함 카테고리: {group?.categories.join(', ')}</div>
                        <div>해당하는 품목: {itemCount}개</div>
                      </div>
                    </div>
                  );
                })()}
              </>
            )}

            {/* 개별 품목 선택 */}
            {formData.mappingType === 'individual' && (
              <div>
                <Label>품목 선택</Label>
                <Select
                  value={formData.itemCode}
                  onValueChange={handleSelectItem}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="품목 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    {itemMasters.map(item => (
                      <SelectItem key={item.id} value={item.itemCode}>
                        {item.itemCode} - {item.itemName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {formData.basePrice !== undefined && (
                  <p className="text-xs text-muted-foreground mt-1">
                    기준 단가: {formData.basePrice.toLocaleString()}원
                  </p>
                )}
              </div>
            )}

            {/* 단가 계산 수식 */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <Label>단가 계산 수식 *</Label>
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setShowVariablePicker(!showVariablePicker)}
                  >
                    변수 검색
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setShowFormulaHelper(!showFormulaHelper)}
                  >
                    함수 도움말
                  </Button>
                </div>
              </div>
              <Input
                id="priceFormula"
                value={priceFormula}
                onChange={(e) => {
                  setPriceFormula(e.target.value);
                  const validation = validateFormula(e.target.value);
                  setFormulaValidation(validation);
                }}
                placeholder="예: W0 * H0 / 1000000"
                className={!formulaValidation.valid && priceFormula ? 'border-red-500 focus-visible:ring-red-500' : ''}
              />
              
              {/* Validation 메시지 */}
              {!formulaValidation.valid && priceFormula && (
                <div className="flex items-start gap-2 p-2 bg-red-50 border border-red-200 rounded text-sm text-red-700 mt-2">
                  <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
                  <span>{formulaValidation.error}</span>
                </div>
              )}
              
              {/* 사용된 변수 표시 */}
              {priceFormula && formulaValidation.valid && (
                <div className="text-xs text-muted-foreground mt-2">
                  <span className="font-medium">사용된 변수:</span>{" "}
                  {extractVariables(priceFormula).length > 0 ? (
                    extractVariables(priceFormula).map((v, i) => (
                      <code key={i} className="bg-gray-100 px-1.5 py-0.5 rounded mr-1">
                        {v}
                      </code>
                    ))
                  ) : (
                    <span>없음</span>
                  )}
                </div>
              )}
            </div>

            {/* 함수 도움말 */}
            {showFormulaHelper && (
              <div>
                <FormulaHelper 
                  onInsertFunction={(syntax) => {
                    const input = document.getElementById("priceFormula") as HTMLInputElement;
                    if (input) {
                      const cursorPos = input.selectionStart || priceFormula.length;
                      const before = priceFormula.substring(0, cursorPos);
                      const after = priceFormula.substring(cursorPos);
                      const newFormula = before + syntax + after;
                      setPriceFormula(newFormula);
                      
                      setTimeout(() => {
                        const validation = validateFormula(newFormula);
                        setFormulaValidation(validation);
                      }, 0);
                    }
                  }}
                />
              </div>
            )}

            {/* 변수 검색 팝오버 */}
            {showVariablePicker && (
              <div className="border rounded-lg p-4 bg-white shadow-lg">
                <div className="flex items-center justify-between mb-3">
                  <Label>등록된 변수 검색</Label>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setShowVariablePicker(false);
                      setVariableSearchQuery("");
                    }}
                    className="h-8 w-8 p-0"
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
                
                <Input
                  placeholder="변수명 또는 이름으로 검색..."
                  value={variableSearchQuery}
                  onChange={(e) => setVariableSearchQuery(e.target.value)}
                  className="mb-3"
                  autoFocus
                />
                
                <div className="max-h-60 overflow-y-auto space-y-1">
                  {/* 시스템 변수 섹션 */}
                  {(() => {
                    const systemVariables = [
                      { variable: "UP", name: "품목 판매단가", category: "시스템" }
                    ];
                    
                    const filteredSystemVars = systemVariables.filter(v => 
                      !variableSearchQuery || 
                      v.variable.toLowerCase().includes(variableSearchQuery.toLowerCase()) ||
                      v.name.toLowerCase().includes(variableSearchQuery.toLowerCase())
                    );
                    
                    return filteredSystemVars.length > 0 && (
                      <div className="mb-2">
                        <div className="flex items-center gap-2 mb-2 px-2">
                          <span className="text-xs font-semibold text-gray-700">시스템 변수</span>
                        </div>
                        {filteredSystemVars.map((v, idx) => (
                          <button
                            key={`system-${idx}`}
                            type="button"
                            onClick={() => handleInsertVariable(v.variable)}
                            className="w-full flex items-center justify-between p-2 hover:bg-orange-50 rounded transition-colors text-left border-l-2 border-orange-400"
                          >
                            <div className="flex items-center gap-2">
                              <code className="bg-orange-100 px-2 py-1 rounded text-sm font-medium text-orange-700">
                                {v.variable}
                              </code>
                              <span className="text-sm text-gray-600">{v.name}</span>
                            </div>
                            <Badge variant="outline" className="text-xs bg-orange-50 text-orange-700 border-orange-300">
                              {v.category}
                            </Badge>
                          </button>
                        ))}
                      </div>
                    );
                  })()}
                  
                  {filteredVariables.length === 0 && variableSearchQuery && (
                    <div className="text-center py-4 text-gray-500 text-sm">
                      검색 결과가 없습니다.
                    </div>
                  )}
                  
                  {filteredVariables.length === 0 && !variableSearchQuery && (
                    <div className="text-center py-4 text-gray-500 text-sm">
                      등록된 변수가 없습니다.
                    </div>
                  )}
                  
                  {filteredVariables.length > 0 && (
                    filteredVariables.map((v, idx) => (
                      <button
                        key={idx}
                        type="button"
                        onClick={() => handleInsertVariable(v.variable)}
                        className="w-full flex items-center justify-between p-2 hover:bg-gray-100 rounded transition-colors text-left"
                      >
                        <div className="flex items-center gap-2">
                          <code className="bg-gray-100 px-2 py-1 rounded text-sm font-medium">
                            {v.variable}
                          </code>
                          <span className="text-sm text-gray-600">{v.name}</span>
                        </div>
                        <Badge variant="outline" className="text-xs">
                          {v.category}
                        </Badge>
                      </button>
                    ))
                  )}
                </div>
              </div>
            )}

            {/* 설명 */}
            <div>
              <Label>설명 (선택)</Label>
              <Textarea
                value={formData.description || ''}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                placeholder="단가 수식 연결에 대한 설명"
                rows={2}
              />
            </div>

            {/* 활성화 */}
            <div className="flex items-center gap-2">
              <Checkbox
                checked={formData.enabled}
                onCheckedChange={(checked) => setFormData(prev => ({ ...prev, enabled: !!checked }))}
              />
              <Label>활성화</Label>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
              취소
            </Button>
            <Button onClick={handleSave}>
              {editingMapping ? '수정' : '추가'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}