"use client";

import React, { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Plus, Pencil, Trash2, Search, Save, RefreshCw, Check, ChevronsUpDown, X } from "lucide-react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import {
  categoryValueCascadingApi,
  CategoryValueCascadingGroup,
  CategoryValueCascadingGroupInput,
  CategoryValueCascadingMappingInput,
} from "@/lib/api/categoryValueCascading";
import { tableManagementApi } from "@/lib/api/tableManagement";

interface TableInfo {
  tableName: string;
  displayName: string;
  description?: string;
  columnCount?: number;
}

interface ColumnInfo {
  columnName: string;
  displayName: string;
  dataType?: string;
  inputType?: string;
  input_type?: string;
}

interface CategoryValue {
  value: string;
  label: string;
}

export default function CategoryValueCascadingTab() {
  // 상태
  const [groups, setGroups] = useState<CategoryValueCascadingGroup[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 테이블/컬럼 목록
  const [tables, setTables] = useState<TableInfo[]>([]);
  const [parentColumns, setParentColumns] = useState<ColumnInfo[]>([]);
  const [childColumns, setChildColumns] = useState<ColumnInfo[]>([]);

  // Combobox 상태
  const [parentTableOpen, setParentTableOpen] = useState(false);
  const [childTableOpen, setChildTableOpen] = useState(false);

  // 모달 상태
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isMappingModalOpen, setIsMappingModalOpen] = useState(false);
  const [selectedGroup, setSelectedGroup] = useState<CategoryValueCascadingGroup | null>(null);

  // 폼 상태
  const [formData, setFormData] = useState<CategoryValueCascadingGroupInput>({
    relationCode: "",
    relationName: "",
    description: "",
    parentTableName: "",
    parentColumnName: "",
    childTableName: "",
    childColumnName: "",
    clearOnParentChange: true,
    showGroupLabel: true,
    emptyParentMessage: "상위 항목을 먼저 선택하세요",
    noOptionsMessage: "선택 가능한 항목이 없습니다",
  });

  // 매핑 상태
  const [parentValues, setParentValues] = useState<CategoryValue[]>([]);
  const [childValues, setChildValues] = useState<CategoryValue[]>([]);
  const [mappings, setMappings] = useState<Record<string, Set<string>>>({});
  const [savingMappings, setSavingMappings] = useState(false);
  
  // 직접 입력 매핑 상태 (각 부모값에 대한 하위 옵션 목록)
  const [childOptionsMap, setChildOptionsMap] = useState<Record<string, { code: string; label: string }[]>>({});
  const [newOptionInputs, setNewOptionInputs] = useState<Record<string, string>>({});

  // 검색
  const [searchText, setSearchText] = useState("");

  // 그룹 목록 로드
  const loadGroups = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await categoryValueCascadingApi.getGroups("Y");
      if (response.success && response.data) {
        setGroups(response.data);
      } else {
        setError(response.error || "그룹 목록 로드 실패");
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

  // 테이블 목록 로드
  const loadTables = useCallback(async () => {
    try {
      console.log("📦 테이블 목록 로드 시작");
      const response = await tableManagementApi.getTableList();
      console.log("📦 테이블 목록 응답:", response);
      if (response.success && response.data) {
        console.log("✅ 테이블 목록 로드 성공:", response.data.length, "개");
        setTables(response.data);
      } else {
        console.error("❌ 테이블 목록 로드 실패:", response);
      }
    } catch (err: any) {
      console.error("테이블 목록 로드 실패:", err);
    }
  }, []);

  // 컬럼 목록 로드
  const loadColumns = useCallback(async (tableName: string, target: "parent" | "child") => {
    if (!tableName) {
      if (target === "parent") setParentColumns([]);
      else setChildColumns([]);
      return;
    }

    try {
      const response = await tableManagementApi.getColumnList(tableName);
      if (response.success && response.data) {
        // API 응답 형식: { columns: [...], total, page, ... }
        const columns = response.data.columns || response.data;
        const columnsArray = Array.isArray(columns) ? columns : [];
        
        // category 타입 컬럼만 필터링
        const categoryColumns = columnsArray.filter(
          (col: any) => col.input_type === "category" || col.inputType === "category"
        );
        
        // 인터페이스에 맞게 변환
        const mappedColumns: ColumnInfo[] = categoryColumns.map((col: any) => ({
          columnName: col.columnName || col.column_name,
          displayName: col.displayName || col.column_label || col.columnName || col.column_name,
          dataType: col.dataType || col.data_type,
          inputType: col.inputType || col.input_type,
        }));
        
        if (target === "parent") setParentColumns(mappedColumns);
        else setChildColumns(mappedColumns);
      }
    } catch (err: any) {
      console.error("컬럼 목록 로드 실패:", err);
    }
  }, []);

  // 초기 로드
  useEffect(() => {
    loadGroups();
    loadTables();
  }, [loadGroups, loadTables]);

  // 필터링된 그룹
  const filteredGroups = groups.filter((group) => {
    if (!searchText) return true;
    const lowerSearch = searchText.toLowerCase();
    return (
      group.relation_code.toLowerCase().includes(lowerSearch) ||
      group.relation_name.toLowerCase().includes(lowerSearch) ||
      group.parent_table_name.toLowerCase().includes(lowerSearch) ||
      group.child_table_name.toLowerCase().includes(lowerSearch)
    );
  });

  // 폼 초기화
  const resetForm = () => {
    // 자동 관계코드 생성
    const autoCode = `CVC_${Date.now()}`;
    setFormData({
      relationCode: autoCode,
      relationName: "",
      description: "",
      parentTableName: "",
      parentColumnName: "",
      childTableName: "",
      childColumnName: "",
      clearOnParentChange: true,
      showGroupLabel: true,
      emptyParentMessage: "상위 항목을 먼저 선택하세요",
      noOptionsMessage: "선택 가능한 항목이 없습니다",
    });
    setParentColumns([]);
    setChildColumns([]);
  };

  // 생성 모달 열기
  const openCreateModal = async () => {
    resetForm();
    // 테이블 목록이 없으면 다시 로드
    if (tables.length === 0) {
      console.log("📦 테이블 목록이 비어있어서 다시 로드");
      await loadTables();
    }
    setIsCreateModalOpen(true);
  };

  // 수정 모달 열기
  const openEditModal = (group: CategoryValueCascadingGroup) => {
    setSelectedGroup(group);
    setFormData({
      relationCode: group.relation_code,
      relationName: group.relation_name,
      description: group.description || "",
      parentTableName: group.parent_table_name,
      parentColumnName: group.parent_column_name,
      childTableName: group.child_table_name,
      childColumnName: group.child_column_name,
      clearOnParentChange: group.clear_on_parent_change === "Y",
      showGroupLabel: group.show_group_label === "Y",
      emptyParentMessage: group.empty_parent_message || "",
      noOptionsMessage: group.no_options_message || "",
    });
    loadColumns(group.parent_table_name, "parent");
    loadColumns(group.child_table_name, "child");
    setIsEditModalOpen(true);
  };

  // 매핑 모달 열기
  const openMappingModal = async (group: CategoryValueCascadingGroup) => {
    setSelectedGroup(group);
    setMappings({});
    setParentValues([]);
    setChildValues([]);
    setChildOptionsMap({});
    setNewOptionInputs({});

    try {
      // 부모 카테고리 값과 기존 매핑 로드
      const [parentResponse, groupDetailResponse] = await Promise.all([
        categoryValueCascadingApi.getParentOptions(group.relation_code),
        categoryValueCascadingApi.getGroupById(group.group_id),
      ]);

      if (parentResponse.success && parentResponse.data) {
        setParentValues(parentResponse.data);
        
        // 부모 값별 입력창 초기화
        const inputs: Record<string, string> = {};
        for (const pv of parentResponse.data) {
          inputs[pv.value] = "";
        }
        setNewOptionInputs(inputs);
      }

      // 기존 매핑을 직접 입력 형태로 변환
      if (groupDetailResponse.success && groupDetailResponse.data?.mappings) {
        const optionsMap: Record<string, { code: string; label: string }[]> = {};
        
        for (const mapping of groupDetailResponse.data.mappings) {
          const parentCode = mapping.parent_value_code;
          if (!optionsMap[parentCode]) {
            optionsMap[parentCode] = [];
          }
          // 중복 체크
          if (!optionsMap[parentCode].some(opt => opt.code === mapping.child_value_code)) {
            optionsMap[parentCode].push({
              code: mapping.child_value_code,
              label: mapping.child_value_label || mapping.child_value_code,
            });
          }
        }
        setChildOptionsMap(optionsMap);
      }

      setIsMappingModalOpen(true);
    } catch (err: any) {
      console.error("매핑 데이터 로드 실패:", err);
      setError("매핑 데이터 로드 실패");
    }
  };

  // 고유 코드 생성 함수
  const generateUniqueCode = () => {
    const timestamp = Date.now().toString(36).toUpperCase();
    const random = Math.random().toString(36).substring(2, 6).toUpperCase();
    return `TARGET_${timestamp}${random}`;
  };

  // 하위 옵션 추가
  const addChildOption = (parentValue: string) => {
    const inputValue = newOptionInputs[parentValue]?.trim();
    if (!inputValue) return;

    // 자동 고유 코드 생성
    const code = generateUniqueCode();

    setChildOptionsMap((prev) => {
      const currentOptions = prev[parentValue] || [];
      // 중복 체크 (라벨만 체크 - 코드는 항상 고유)
      if (currentOptions.some((opt) => opt.label === inputValue)) {
        return prev;
      }
      return {
        ...prev,
        [parentValue]: [...currentOptions, { code, label: inputValue }],
      };
    });

    // 입력창 초기화
    setNewOptionInputs((prev) => ({ ...prev, [parentValue]: "" }));
  };

  // 하위 옵션 삭제
  const removeChildOption = (parentValue: string, optionCode: string) => {
    setChildOptionsMap((prev) => ({
      ...prev,
      [parentValue]: (prev[parentValue] || []).filter((opt) => opt.code !== optionCode),
    }));
  };

  // 그룹 생성
  const handleCreate = async () => {
    try {
      const response = await categoryValueCascadingApi.createGroup(formData);
      if (response.success) {
        setIsCreateModalOpen(false);
        loadGroups();
      } else {
        setError(response.error || "생성 실패");
      }
    } catch (err: any) {
      setError(err.message);
    }
  };

  // 그룹 수정
  const handleUpdate = async () => {
    if (!selectedGroup) return;

    try {
      const response = await categoryValueCascadingApi.updateGroup(selectedGroup.group_id, formData);
      if (response.success) {
        setIsEditModalOpen(false);
        loadGroups();
      } else {
        setError(response.error || "수정 실패");
      }
    } catch (err: any) {
      setError(err.message);
    }
  };

  // 그룹 삭제
  const handleDelete = async (group: CategoryValueCascadingGroup) => {
    if (!confirm(`"${group.relation_name}" 연쇄관계를 삭제하시겠습니까?`)) return;

    try {
      const response = await categoryValueCascadingApi.deleteGroup(group.group_id);
      if (response.success) {
        loadGroups();
      } else {
        setError(response.error || "삭제 실패");
      }
    } catch (err: any) {
      setError(err.message);
    }
  };

  // 매핑 토글
  const toggleMapping = (parentCode: string, childCode: string) => {
    setMappings((prev) => {
      const newMappings = { ...prev };
      if (!newMappings[parentCode]) {
        newMappings[parentCode] = new Set();
      }

      const newSet = new Set(newMappings[parentCode]);
      if (newSet.has(childCode)) {
        newSet.delete(childCode);
      } else {
        newSet.add(childCode);
      }
      newMappings[parentCode] = newSet;

      return newMappings;
    });
  };

  // 매핑 저장
  const handleSaveMappings = async () => {
    if (!selectedGroup) return;

    setSavingMappings(true);
    try {
      // 직접 입력된 옵션으로 매핑 데이터 생성
      const mappingInputs: CategoryValueCascadingMappingInput[] = [];
      let displayOrder = 0;

      for (const parentCode of Object.keys(childOptionsMap)) {
        const parentValue = parentValues.find((p) => p.value === parentCode);
        const childOptions = childOptionsMap[parentCode] || [];

        for (const childOption of childOptions) {
          mappingInputs.push({
            parentValueCode: parentCode,
            parentValueLabel: parentValue?.label,
            childValueCode: childOption.code,
            childValueLabel: childOption.label,
            displayOrder: displayOrder++,
          });
        }
      }

      const response = await categoryValueCascadingApi.saveMappings(
        selectedGroup.group_id,
        mappingInputs
      );

      if (response.success) {
        setIsMappingModalOpen(false);
      } else {
        setError(response.error || "매핑 저장 실패");
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSavingMappings(false);
    }
  };

  // 활성/비활성 토글
  const toggleActive = async (group: CategoryValueCascadingGroup) => {
    try {
      const newActive = group.is_active !== "Y";
      const response = await categoryValueCascadingApi.updateGroup(group.group_id, {
        isActive: newActive,
      });
      if (response.success) {
        loadGroups();
      }
    } catch (err: any) {
      setError(err.message);
    }
  };

  return (
    <div className="space-y-6">
      {/* 설명 */}
      <div className="space-y-2">
        <h2 className="text-xl font-semibold">카테고리 값 연쇄관계</h2>
        <p className="text-sm text-muted-foreground">
          카테고리 값들 간의 부모-자식 연쇄관계를 정의합니다. 예: 검사유형 선택 시 해당 유형에 맞는 적용대상만 표시
        </p>
      </div>

      {/* 에러 메시지 */}
      {error && (
        <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4">
          <div className="flex items-center justify-between">
            <p className="text-sm font-semibold text-destructive">오류</p>
            <button onClick={() => setError(null)} className="text-destructive hover:text-destructive/80">
              x
            </button>
          </div>
          <p className="mt-1 text-sm text-destructive/80">{error}</p>
        </div>
      )}

      {/* 검색 및 액션 */}
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
          <div className="relative w-full sm:w-[300px]">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="관계코드, 관계명, 테이블명 검색..."
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              className="h-10 pl-10 text-sm"
            />
          </div>
        </div>

        <div className="flex items-center gap-4">
          <div className="text-sm text-muted-foreground">
            총 <span className="font-semibold text-foreground">{filteredGroups.length}</span> 건
          </div>
          <Button onClick={() => loadGroups()} variant="outline" className="h-10 gap-2 text-sm font-medium">
            <RefreshCw className="h-4 w-4" />
            새로고침
          </Button>
          <Button onClick={openCreateModal} className="h-10 gap-2 text-sm font-medium">
            <Plus className="h-4 w-4" />
            등록
          </Button>
        </div>
      </div>

      {/* 테이블 */}
      <div className="rounded-lg border bg-card shadow-sm">
        <Table>
          <TableHeader>
            <TableRow className="border-b bg-muted/50 hover:bg-muted/50">
              <TableHead className="h-12 text-sm font-semibold">관계코드</TableHead>
              <TableHead className="h-12 text-sm font-semibold">관계명</TableHead>
              <TableHead className="h-12 text-sm font-semibold">부모 (테이블.컬럼)</TableHead>
              <TableHead className="h-12 text-sm font-semibold">자식 (테이블.컬럼)</TableHead>
              <TableHead className="h-12 text-sm font-semibold">사용</TableHead>
              <TableHead className="h-12 text-sm font-semibold text-center">관리</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              Array.from({ length: 5 }).map((_, idx) => (
                <TableRow key={idx} className="border-b">
                  <TableCell className="h-16">
                    <div className="h-4 w-24 animate-pulse rounded bg-muted" />
                  </TableCell>
                  <TableCell className="h-16">
                    <div className="h-4 w-32 animate-pulse rounded bg-muted" />
                  </TableCell>
                  <TableCell className="h-16">
                    <div className="h-4 w-40 animate-pulse rounded bg-muted" />
                  </TableCell>
                  <TableCell className="h-16">
                    <div className="h-4 w-40 animate-pulse rounded bg-muted" />
                  </TableCell>
                  <TableCell className="h-16">
                    <div className="h-6 w-11 animate-pulse rounded-full bg-muted" />
                  </TableCell>
                  <TableCell className="h-16">
                    <div className="h-8 w-24 animate-pulse rounded bg-muted" />
                  </TableCell>
                </TableRow>
              ))
            ) : filteredGroups.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="h-32 text-center text-sm text-muted-foreground">
                  등록된 카테고리 값 연쇄관계가 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              filteredGroups.map((group) => (
                <TableRow key={group.group_id} className="border-b transition-colors hover:bg-muted/50">
                  <TableCell className="h-16 text-sm font-mono">{group.relation_code}</TableCell>
                  <TableCell className="h-16 text-sm font-medium">{group.relation_name}</TableCell>
                  <TableCell className="h-16 text-sm">
                    <span className="text-muted-foreground">{group.parent_table_name}.</span>
                    {group.parent_column_name}
                  </TableCell>
                  <TableCell className="h-16 text-sm">
                    <span className="text-muted-foreground">{group.child_table_name}.</span>
                    {group.child_column_name}
                  </TableCell>
                  <TableCell className="h-16">
                    <Switch
                      checked={group.is_active === "Y"}
                      onCheckedChange={() => toggleActive(group)}
                      aria-label="활성화 토글"
                    />
                  </TableCell>
                  <TableCell className="h-16">
                    <div className="flex items-center justify-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openMappingModal(group)}
                        className="h-8 gap-1 text-xs"
                      >
                        값 매핑
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => openEditModal(group)}
                        className="h-8 w-8"
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleDelete(group)}
                        className="h-8 w-8 text-destructive hover:text-destructive"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 생성 모달 */}
      <Dialog open={isCreateModalOpen} onOpenChange={setIsCreateModalOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle className="text-base sm:text-lg">카테고리 값 연쇄관계 등록</DialogTitle>
            <DialogDescription className="text-xs sm:text-sm">
              카테고리 값들 간의 부모-자식 연쇄관계를 정의합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 기본 정보 */}
            <div className="space-y-2">
              <Label className="text-xs sm:text-sm">관계명 *</Label>
              <Input
                value={formData.relationName}
                onChange={(e) => setFormData({ ...formData, relationName: e.target.value })}
                placeholder="예: 검사유형-적용대상"
                className="h-8 text-xs sm:h-10 sm:text-sm"
              />
            </div>

            <div className="space-y-2">
              <Label className="text-xs sm:text-sm">설명</Label>
              <Input
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="연쇄관계 설명"
                className="h-8 text-xs sm:h-10 sm:text-sm"
              />
            </div>

            {/* 부모 설정 */}
            <div className="space-y-2 rounded-md border p-3">
              <h4 className="text-sm font-medium">부모 카테고리 설정</h4>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label className="text-xs">테이블 *</Label>
                  <Popover open={parentTableOpen} onOpenChange={setParentTableOpen}>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        aria-expanded={parentTableOpen}
                        className="h-8 w-full justify-between text-xs sm:h-10 sm:text-sm"
                      >
                        {formData.parentTableName
                          ? tables.find((t) => t.tableName === formData.parentTableName)?.displayName ||
                            formData.parentTableName
                          : "테이블 검색..."}
                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[300px] p-0" align="start">
                      <Command>
                        <CommandInput placeholder="테이블 검색..." className="text-xs sm:text-sm" />
                        <CommandList>
                          <CommandEmpty className="py-2 text-center text-xs text-muted-foreground">
                            {tables.length === 0 ? "테이블을 불러오는 중..." : "테이블을 찾을 수 없습니다."}
                          </CommandEmpty>
                          <CommandGroup>
                            {tables.map((table) => (
                              <CommandItem
                                key={table.tableName}
                                value={`${table.displayName || ""} ${table.tableName}`}
                                onSelect={() => {
                                  setFormData({ ...formData, parentTableName: table.tableName, parentColumnName: "", childTableName: table.tableName });
                                  loadColumns(table.tableName, "parent");
                                  setParentTableOpen(false);
                                }}
                                className="text-xs sm:text-sm"
                              >
                                <Check
                                  className={cn(
                                    "mr-2 h-4 w-4",
                                    formData.parentTableName === table.tableName ? "opacity-100" : "opacity-0"
                                  )}
                                />
                                <div className="flex flex-col">
                                  <span className="font-medium">{table.displayName || table.tableName}</span>
                                  {table.displayName && table.displayName !== table.tableName && (
                                    <span className="text-[10px] text-muted-foreground">{table.tableName}</span>
                                  )}
                                </div>
                              </CommandItem>
                            ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                </div>
                <div className="space-y-2">
                  <Label className="text-xs">카테고리 컬럼 *</Label>
                  <Select
                    value={formData.parentColumnName}
                    onValueChange={(value) => setFormData({ ...formData, parentColumnName: value })}
                    disabled={!formData.parentTableName}
                  >
                    <SelectTrigger className="h-8 text-xs sm:h-10 sm:text-sm">
                      <SelectValue placeholder="컬럼 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {parentColumns.length === 0 ? (
                        <div className="px-2 py-1 text-xs text-muted-foreground">
                          {formData.parentTableName ? "카테고리 컬럼이 없습니다" : "테이블을 먼저 선택하세요"}
                        </div>
                      ) : (
                        parentColumns.map((col) => (
                          <SelectItem key={col.columnName} value={col.columnName}>
                            {col.displayName || col.columnName}
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* 자식 옵션 라벨 설정 */}
            <div className="space-y-2 rounded-md border p-3">
              <h4 className="text-sm font-medium">하위 옵션 설정</h4>
              <p className="text-xs text-muted-foreground">
                부모 카테고리 값별로 표시할 하위 옵션들의 그룹명을 입력합니다.
                <br />
                실제 하위 옵션은 등록 후 "값 매핑" 버튼에서 직접 입력합니다.
              </p>
              <div className="space-y-2">
                <Label className="text-xs">하위 옵션 라벨 *</Label>
                <Input
                  value={formData.childColumnName}
                  onChange={(e) => setFormData({ ...formData, childColumnName: e.target.value, childTableName: formData.parentTableName })}
                  placeholder="예: 적용대상"
                  className="h-8 text-xs sm:h-10 sm:text-sm"
                />
              </div>
            </div>

            {/* 옵션 */}
            <div className="flex items-center gap-6">
              <label className="flex items-center gap-2">
                <Checkbox
                  checked={formData.clearOnParentChange}
                  onCheckedChange={(checked) => setFormData({ ...formData, clearOnParentChange: !!checked })}
                />
                <span className="text-sm">부모 변경 시 자식 초기화</span>
              </label>
              <label className="flex items-center gap-2">
                <Checkbox
                  checked={formData.showGroupLabel}
                  onCheckedChange={(checked) => setFormData({ ...formData, showGroupLabel: !!checked })}
                />
                <span className="text-sm">그룹 라벨 표시</span>
              </label>
            </div>
          </div>

          <DialogFooter className="gap-2 sm:gap-0">
            <Button
              variant="outline"
              onClick={() => setIsCreateModalOpen(false)}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              취소
            </Button>
            <Button
              onClick={handleCreate}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
              disabled={!formData.relationCode || !formData.relationName || !formData.parentTableName || !formData.parentColumnName || !formData.childColumnName}
            >
              등록
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 수정 모달 */}
      <Dialog open={isEditModalOpen} onOpenChange={setIsEditModalOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle className="text-base sm:text-lg">카테고리 값 연쇄관계 수정</DialogTitle>
            <DialogDescription className="text-xs sm:text-sm">
              연쇄관계 설정을 수정합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* 기본 정보 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="text-xs sm:text-sm">관계코드</Label>
                <Input
                  value={formData.relationCode}
                  disabled
                  className="h-8 text-xs sm:h-10 sm:text-sm bg-muted"
                />
              </div>
              <div className="space-y-2">
                <Label className="text-xs sm:text-sm">관계명 *</Label>
                <Input
                  value={formData.relationName}
                  onChange={(e) => setFormData({ ...formData, relationName: e.target.value })}
                  className="h-8 text-xs sm:h-10 sm:text-sm"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label className="text-xs sm:text-sm">설명</Label>
              <Input
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                className="h-8 text-xs sm:h-10 sm:text-sm"
              />
            </div>

            {/* 부모/자식 설정 - 수정 불가 표시 */}
            <div className="space-y-2 rounded-md border p-3 bg-muted/30">
              <h4 className="text-sm font-medium text-muted-foreground">부모/자식 설정 (수정 불가)</h4>
              <div className="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">부모: </span>
                  {formData.parentTableName}.{formData.parentColumnName}
                </div>
                <div>
                  <span className="text-muted-foreground">자식: </span>
                  {formData.childTableName}.{formData.childColumnName}
                </div>
              </div>
            </div>

            {/* 옵션 */}
            <div className="flex items-center gap-6">
              <label className="flex items-center gap-2">
                <Checkbox
                  checked={formData.clearOnParentChange}
                  onCheckedChange={(checked) => setFormData({ ...formData, clearOnParentChange: !!checked })}
                />
                <span className="text-sm">부모 변경 시 자식 초기화</span>
              </label>
              <label className="flex items-center gap-2">
                <Checkbox
                  checked={formData.showGroupLabel}
                  onCheckedChange={(checked) => setFormData({ ...formData, showGroupLabel: !!checked })}
                />
                <span className="text-sm">그룹 라벨 표시</span>
              </label>
            </div>
          </div>

          <DialogFooter className="gap-2 sm:gap-0">
            <Button
              variant="outline"
              onClick={() => setIsEditModalOpen(false)}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              취소
            </Button>
            <Button
              onClick={handleUpdate}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 값 매핑 모달 */}
      <Dialog open={isMappingModalOpen} onOpenChange={setIsMappingModalOpen}>
        <DialogContent className="max-w-[95vw] sm:max-w-[800px] max-h-[90vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle className="text-base sm:text-lg">
              하위 옵션 설정 - {selectedGroup?.relation_name}
            </DialogTitle>
            <DialogDescription className="text-xs sm:text-sm">
              각 부모 카테고리 값에 대해 하위 옵션을 직접 입력합니다.
            </DialogDescription>
          </DialogHeader>

          <div className="flex-1 overflow-auto">
            {parentValues.length === 0 ? (
              <div className="flex h-32 items-center justify-center text-sm text-muted-foreground">
                부모 카테고리 값이 등록되지 않았습니다.
                <br />
                먼저 카테고리 관리에서 "{selectedGroup?.parent_column_name}" 컬럼의 값을 등록하세요.
              </div>
            ) : (
              <div className="space-y-4">
                {parentValues.map((parent) => (
                  <div key={parent.value} className="space-y-3 rounded-md border p-4">
                    <div className="flex items-center justify-between">
                      <h4 className="text-sm font-semibold">{parent.label}</h4>
                      <span className="text-xs text-muted-foreground">
                        {(childOptionsMap[parent.value] || []).length}개 옵션
                      </span>
                    </div>
                    
                    {/* 하위 옵션 입력 */}
                    <div className="flex gap-2">
                      <Input
                        value={newOptionInputs[parent.value] || ""}
                        onChange={(e) =>
                          setNewOptionInputs((prev) => ({ ...prev, [parent.value]: e.target.value }))
                        }
                        onKeyDown={(e) => {
                          // 한글 IME 조합 중에는 무시 (마지막 글자 중복 방지)
                          if (e.nativeEvent.isComposing) return;
                          if (e.key === "Enter") {
                            e.preventDefault();
                            addChildOption(parent.value);
                          }
                        }}
                        placeholder="하위 옵션 입력 후 Enter 또는 추가 버튼"
                        className="h-8 flex-1 text-xs sm:h-10 sm:text-sm"
                      />
                      <Button
                        size="sm"
                        onClick={() => addChildOption(parent.value)}
                        className="h-8 sm:h-10"
                      >
                        <Plus className="h-4 w-4" />
                      </Button>
                    </div>
                    
                    {/* 등록된 하위 옵션 목록 */}
                    <div className="flex flex-wrap gap-2">
                      {(childOptionsMap[parent.value] || []).map((option) => (
                        <div
                          key={option.code}
                          className="flex items-center gap-1 rounded-md bg-muted px-2 py-1"
                        >
                          <span className="text-xs">{option.label}</span>
                          <button
                            type="button"
                            onClick={() => removeChildOption(parent.value, option.code)}
                            className="rounded-full hover:bg-muted-foreground/20 p-0.5"
                          >
                            <X className="h-3 w-3 text-muted-foreground" />
                          </button>
                        </div>
                      ))}
                      {(childOptionsMap[parent.value] || []).length === 0 && (
                        <span className="text-xs text-muted-foreground">등록된 하위 옵션이 없습니다</span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <DialogFooter className="gap-2 sm:gap-0 border-t pt-4">
            <Button
              variant="outline"
              onClick={() => setIsMappingModalOpen(false)}
              className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              취소
            </Button>
            <Button
              onClick={handleSaveMappings}
              disabled={savingMappings}
              className="h-8 flex-1 gap-2 text-xs sm:h-10 sm:flex-none sm:text-sm"
            >
              <Save className="h-4 w-4" />
              {savingMappings ? "저장 중..." : "저장"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

