'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useQuery } from '@tanstack/react-query'
import { useSuitable } from '@/hooks/useSuitable'

export default function SuitableSearch() {
  const router = useRouter()
  const [selectedCategory, setSelectedCategory] = useState<string>('')
  const [searchValue, setSearchValue] = useState<string>('')
  const { getCategories, getSuitables } = useSuitable()

  const { data: categories } = useQuery({
    queryKey: ['categories'],
    queryFn: getCategories,
    staleTime: 1000 * 60 * 60, // 60분
  })

  const { data: suitableList } = useQuery({
    queryKey: ['suitables', 'list'],
    queryFn: async () => await getSuitables(),
    staleTime: 1000 * 60 * 10, // 10분
    gcTime: 1000 * 60 * 10, // 10분
  })

  const { data: suitableSearch, refetch: refetchBySearch } = useQuery({
    queryKey: ['suitables', 'search'],
    queryFn: async () => {
      // api를 호출하는 검색 방법
      // return await updateSearchResults(selectedCategory || undefined, searchValue || undefined)
      // useQuery 캐시 데이터를 사용하는 검색 방법
      return (
        suitableList?.filter((item) => {
          const categoryMatch = !selectedCategory || item.roof_material === selectedCategory
          const searchMatch = !searchValue || item.product_name.includes(searchValue)
          return categoryMatch && searchMatch
        }) ?? []
      )
    },
    staleTime: 1000 * 60 * 10,
    gcTime: 1000 * 60 * 10,
    enabled: false,
  })

  // 초기 데이터 로딩된 후 검색 결과 없으면 검색 결과 로딩
  useEffect(() => {
    if (suitableList && (!suitableSearch || suitableSearch.length === 0)) {
      refetchBySearch()
    }
  }, [suitableList, suitableSearch])

  // 카테고리 선택 시 검색 결과 로딩
  useEffect(() => {
    refetchBySearch()
  }, [selectedCategory])

  const handleSearch = async () => {
    if (!searchValue.trim()) {
      alert('검색어를 입력하세요.')
      return
    }
    refetchBySearch()
  }

  return (
    <>
      <div>
        <select value={selectedCategory || ''} onChange={(e) => setSelectedCategory(e.target.value)}>
          <option value="">지붕재 카테고리 선택 고고</option>
          {categories?.map((category) => (
            <option key={category.roof_material} value={category.roof_material}>
              {category.roof_material}
            </option>
          ))}
        </select>
        <button onClick={() => router.push(`/suitable/${selectedCategory}`)}> 지붕재 종류 상세보기 페이지 이동</button>
      </div>
      <div>
        <input type="text" placeholder="검색어를 입력하세요" onChange={(e) => setSearchValue(e.target.value)} />
        <button onClick={handleSearch}>검색</button>
      </div>
    </>
  )
}
