import { useEffect, useState } from 'react'
import { DateRange } from 'react-day-picker'

import { AgeCategoryCount, FilterBarTypes, Pages } from '../FilterBarTypes'

type Props = {
  locations: FilterBarTypes['locations']
}

export const useFilterState = ({ locations }: Props) => {
  const [selectedPath, setSelectedPath] = useState<string>(Pages.EVENTS)
  const [selectedFilter, setSelectedFilter] = useState<string | boolean>(false)
  const [calendarRange, setCalendarRange] = useState<DateRange | undefined>()
  const [innerLoading, setInnerLoading] = useState<boolean>(false)
  const [categories, setCategories] = useState<number>(0)
  const [ageCategoryCounts, setAgeCategoryCounts] = useState<AgeCategoryCount>(
    {}
  )
  const [selectedLocations, setSelectedLocations] = useState<
    NonNullable<FilterBarTypes['locations']>['data']
  >([])

  useEffect(() => {
    if (typeof window === 'undefined') return

    const urlSearchParams = new URLSearchParams(window.location.search)

    const startDateParam = urlSearchParams.get('startDate')
    const endDateParam = urlSearchParams.get('endDate')
    const locationIdParams = urlSearchParams.getAll('locationId')

    let ageCategoryCountsParam: AgeCategoryCount = {}
    const ageCategoryCountsQuery = urlSearchParams.get('ageCategoryCounts')

    if (ageCategoryCountsQuery) {
      try {
        ageCategoryCountsParam = JSON.parse(ageCategoryCountsQuery)
      } catch (error) {
        console.warn('Invalid ageCategoryCounts query param, ignoring', error)
        ageCategoryCountsParam = {}
      }
    }

    const categoriesParam = urlSearchParams.get('categories')
    let parsedCategories = 0

    if (categoriesParam) {
      const parsed = parseInt(categoriesParam, 10)
      parsedCategories = Number.isNaN(parsed) ? 0 : parsed
    }

    if (startDateParam && endDateParam) {
      setCalendarRange({
        from: new Date(startDateParam),
        to: new Date(endDateParam),
      })
    }

    setAgeCategoryCounts(ageCategoryCountsParam)
    setCategories(parsedCategories)

    if (locations?.data?.length && locationIdParams.length) {
      const matchedLocations = locations.data.filter((location) =>
        locationIdParams.includes(location.id.toString())
      )
      setSelectedLocations(matchedLocations)
    }
  }, [locations])

  return {
    selectedPath,
    selectedFilter,
    calendarRange,
    innerLoading,
    categories,
    ageCategoryCounts,
    selectedLocations,
    setSelectedLocations,
    setCalendarRange,
    setAgeCategoryCounts,
    setCategories,
    setSelectedPath,
    setSelectedFilter,
    setInnerLoading,
  }
}
