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 SuitableDetail } from '@/types/Suitable'

export type Suitable = {
  id: number
  productName: string
  manuFtCd: string
  roofMtCd: string
  roofShCd: string
  detail: string
}

export function useSuitableRaw() {
  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/test')
      return response.data
    } catch (error) {
      console.error('지붕재 데이터 로드 실패:', error)
      return []
    }
  }

  // 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 = (suitableDetailString: string): SuitableDetail[] => {
    try {
      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<SuitableData>({
  } = useQuery<Suitable[]>({
    queryKey: ['suitables', 'search', selectedCategory, isSearch],
    queryFn: async () => {
      if (!isSearch && !selectedCategory) {
        return isInitialLoading ? await getSuitables() : suitableList ?? [] // 검색 상태가 아니면 초기 데이터 반환 임시처리
      } else {
        return (
          suitableList?.filter((item: Suitable) => {
            const categoryMatch = !selectedCategory || item.roofMtCd === selectedCategory
            const searchMatch = !searchValue || item.productName.includes(searchValue)
            return categoryMatch && searchMatch
          }) ?? []
        )
      }
    },
    staleTime: 1000 * 60 * 10,
    gcTime: 1000 * 60 * 10,
    enabled: true,
  })

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