import { useQuery } from '@tanstack/react-query'
import { find } from 'lodash'
import { toast } from 'react-toastify'
import { useAxios } from './useAxios'

export const getYears = () =>
  useAxios({
    url: 'year',
    method: 'GET',
  })

export type YEAR = {
  year: number
  id?: string
}

const getCurrentYear = () => new Date().getFullYear()

export const useYears = () => {
  const { isLoading, data, refetch } = useQuery(
    ['getYears'],
    () => getYears(),
    {
      onError: (error: { message: string }) => {
        toast(error?.message || 'Failed to fetch years', {
          closeButton: false,
          type: 'error',
          autoClose: 2000,
          hideProgressBar: true,
        })
      },
    },
  )

  const currentYear = find(data?.data || [], { year: getCurrentYear() })

  return {
    isYearDataLoading: isLoading,
    years: data?.data || [],
    currentYear,
    refetchYear: refetch,
  }
}
