import { useCallback, useMemo, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "@/lib/queryKeys";
import type { CodeInfo } from "@/types/commonCode";

/**
 * 선택된 그룹(code_info) 상태 관리 훅
 *
 * 좌측 패널에서 그룹을 클릭하면 selectedCodeInfo 가 갱신되고,
 * 우측 디테일 트리 패널이 그 값을 받아 트리를 로드한다.
 */
export function useSelectedCodeInfo() {
  const queryClient = useQueryClient();
  const [selectedCode, setSelectedCode] = useState<string>("");

  const selectedRow = useMemo<CodeInfo | null>(() => {
    if (!selectedCode) return null;
    const list = queryClient.getQueryData<CodeInfo[]>(queryKeys.codeInfo.list());
    if (!list || !Array.isArray(list)) return null;
    return list.find((row) => row.code_info === selectedCode) || null;
  }, [selectedCode, queryClient]);

  const selectCodeInfo = useCallback((codeInfo: string) => {
    setSelectedCode(codeInfo);
  }, []);

  const clearSelection = useCallback(() => {
    setSelectedCode("");
  }, []);

  return {
    selectedCodeInfo: selectedCode,
    selectedRow,
    hasSelection: Boolean(selectedCode),
    selectCodeInfo,
    clearSelection,
  };
}
