import { useState, useMemo } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import { fetchApi } from '@/api';
import { SEARCH_LIMIT } from '@/constants';

/**
 * 스케줄 검색 훅
 * 무한 스크롤, 검색어 추천 지원
 */
export function useScheduleSearch() {
  const [searchInput, setSearchInput] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [isSearchMode, setIsSearchMode] = useState(false);

  // 검색 결과 (무한 스크롤)
  const searchQuery = useInfiniteQuery({
    queryKey: ['scheduleSearch', searchTerm],
    queryFn: async ({ pageParam = 0, signal }) => {
      const response = await fetch(
        `/api/schedules?search=${encodeURIComponent(searchTerm)}&offset=${pageParam}&limit=${SEARCH_LIMIT}`,
        { signal }
      );
      if (!response.ok) throw new Error('Search failed');
      return response.json();
    },
    getNextPageParam: (lastPage) => {
      return lastPage.hasMore
        ? lastPage.offset + lastPage.schedules.length
        : undefined;
    },
    enabled: !!searchTerm && isSearchMode,
  });

  // 검색 결과 평탄화
  const searchResults = useMemo(() => {
    return searchQuery.data?.pages?.flatMap((page) => page.schedules) || [];
  }, [searchQuery.data]);

  const searchTotal = searchQuery.data?.pages?.[0]?.total || 0;

  // 검색 실행
  const executeSearch = () => {
    if (searchInput.trim()) {
      setSearchTerm(searchInput.trim());
      setIsSearchMode(true);
    }
  };

  // 검색 초기화
  const clearSearch = () => {
    setSearchInput('');
    setSearchTerm('');
    setIsSearchMode(false);
  };

  return {
    // 상태
    searchInput,
    searchTerm,
    isSearchMode,
    searchResults,
    searchTotal,
    isLoading: searchQuery.isLoading,
    isFetching: searchQuery.isFetching,
    hasNextPage: searchQuery.hasNextPage,
    isFetchingNextPage: searchQuery.isFetchingNextPage,

    // 액션
    setSearchInput,
    setIsSearchMode,
    executeSearch,
    clearSearch,
    fetchNextPage: searchQuery.fetchNextPage,
  };
}
