import { useQuery } from '@tanstack/react-query'
import { axiosInstance, transformObjectKeys } from '@/libs/axios'
import { useSuitableStore } from '@/store/useSuitableStore'
import { useCommCode } from './useCommCode'
import { SUITABLE_HEAD_CODE, type SuitableDetailGroup, type SuitableMain, type Suitable, type SuitableDetail } from '@/types/Suitable'

export function useSuitable() {
  const { getCommCode } = useCommCode()
  const { selectedCategory, searchValue, suitableCommCode, setSuitableCommCode, isSearch } = useSuitableStore()

  const getSuitables = async (): Promise<Suitable> => {
    try {
      const response = await axiosInstance(null).get<Suitable>('/api/suitable/list')
      return response.data
    } catch (error) {
      console.error('지붕재 데이터 로드 실패:', error)
      return { suitable: [], detail: [] }
    }
  }

  // const updateSearchResults = async (selectedCategory: string | undefined, searchValue: string | undefined): Promise<SuitableData[]> => {
  //   try {
  //     const response = await axiosInstance(null).get<SuitableData[]>('/api/suitable/list', { params: { selectedCategory, searchValue } })
  //     return response.data
  //   } catch (error) {
  //     console.error('지붕재 데이터 검색 실패:', error)
  //     return []
  //   }
  // }

  const getSuitableCommCode = () => {
    const headCodes = Object.values(SUITABLE_HEAD_CODE) as SUITABLE_HEAD_CODE[]
    for (const code of headCodes) {
      getCommCode(code).then((res) => {
        setSuitableCommCode(code, res)
      })
    }
  }

  const toCodeName = (headCode: string, code: string): string => {
    const commCode = suitableCommCode.get(headCode)
    return commCode?.find((item) => item.code === code)?.codeJp || ''
  }

  const toSuitableDetail = (mainId: number): SuitableDetail[] => {
    try {
      const suitableDetailString = suitableList?.detail.find((item) => item.mainId === mainId)?.detail
      if (!suitableDetailString) {
        return []
      }
      const suitableDetailArray = transformObjectKeys(JSON.parse(suitableDetailString)) as SuitableDetail[]
      if (!Array.isArray(suitableDetailArray)) {
        throw new Error('suitableDetailArray is not an array')
      }
      return suitableDetailArray
    } catch (error) {
      console.error('지붕재 데이터 파싱 실패:', error)
      return []
    }
  }

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

  const {
    data: suitableSearchResults,
    refetch: refetchBySearch,
    isLoading: isSearchLoading,
  } = useQuery<Suitable>({
    queryKey: ['suitables', 'search', selectedCategory, isSearch],
    queryFn: async () => {
      if (!isSearch && !selectedCategory) {
        // 검색 상태가 아니면 초기 데이터 반환 임시처리
        return isInitialLoading ? await getSuitables() : suitableList ?? { suitable: [], detail: [] }
      } else {
        const filteredSuitable = suitableList?.suitable.filter((item: SuitableMain) => {
          const categoryMatch = !selectedCategory || item.roofMtCd === selectedCategory
          const searchMatch = !searchValue || item.productName.includes(searchValue)
          return categoryMatch && searchMatch
        }) ?? []
        const mainIds = filteredSuitable.map((item: SuitableMain) => item.id)
        const filteredDetail = suitableList?.detail.filter((item: SuitableDetailGroup) => {
          return mainIds.includes(item.mainId)
        }) ?? []
        return { suitable: filteredSuitable, detail: filteredDetail }
      }
    },
    staleTime: 1000 * 60 * 10,
    gcTime: 1000 * 60 * 10,
    enabled: true,
  })

  return {
    getSuitables,
    getSuitableCommCode,
    toCodeName,
    toSuitableDetail,
    suitableList,
    suitableSearchResults,
    refetchBySearch,
    isSearchLoading,
  }
}
