import { Dispatch, SetStateAction, useEffect } from 'react'
import { DateRange } from 'react-day-picker'
import { format } from 'date-fns'

import {
  AgeCategoryCount,
  FilterBarTypes,
  Locations,
  Pages,
} from '../FilterBarTypes'
import { ageCategoryRules } from '../utils'

type Props = {
  tabs: FilterBarTypes['tabs']
  ageCategories: FilterBarTypes['ageCategories']
  redirectUrl: FilterBarTypes['redirectUrl']
  ageCategoryCounts: AgeCategoryCount
  selectedLocations: Locations['data']
  calendarRange?: DateRange
  selectedPath: string
  setSelectedPath: (val: string) => void
  setAgeCategoryCounts: Dispatch<SetStateAction<AgeCategoryCount>>
  setSelectedFilter: (val: string | boolean) => void
  setCalendarRange: (val: DateRange | undefined) => void
  onSubmit: FilterBarTypes['onSubmit']
  setInnerLoading: (val: boolean) => void
}

export const useFilterActions = ({
  tabs,
  calendarRange,
  ageCategoryCounts,
  ageCategories,
  selectedLocations,
  selectedPath,
  redirectUrl,
  setSelectedPath,
  setAgeCategoryCounts,
  setSelectedFilter,
  setCalendarRange,
  onSubmit,
  setInnerLoading,
}: Props) => {
  useEffect(() => {
    if (typeof window === 'undefined') return

    const defaultTab =
      tabs?.length === 1 ? tabs[0] : tabs?.find((tab) => tab.default)

    const paths = [Pages.EVENTS, Pages.ROOMS, Pages.SALES]

    const currentPath =
      paths.find((path) => window.location.pathname.includes(path)) ||
      defaultTab?.path ||
      Pages.EVENTS

    setSelectedPath(currentPath)
  }, [tabs])

  const updateGuestsCount = (id: string, newCount: number) => {
    setAgeCategoryCounts((prev) => ({
      ...prev,
      [id]: newCount,
    }))
  }

  const handleSelectedFilter = (id: string | boolean) => {
    setSelectedFilter(id)
  }

  const handleSubmit = () => {
    if (typeof window === 'undefined') return

    const newParams = {
      startDate: calendarRange?.from
        ? format(calendarRange.from, 'yyyy-MM-dd')
        : '',
      endDate: calendarRange?.to ? format(calendarRange.to, 'yyyy-MM-dd') : '',
      ageCategoryCounts: ageCategoryRules({
        ageCategoryCounts,
        ageCategories,
      }),
      selectedLocations: selectedLocations
        .map((l) => l.id.toString())
        .join(','),
    }

    const querySearchParams = new URLSearchParams()

    for (const [key, value] of Object.entries(newParams)) {
      if (!value) continue

      if (key === 'selectedLocations' && selectedLocations.length) {
        selectedLocations.forEach((location) =>
          querySearchParams.append('locationId', location.id.toString())
        )
      } else {
        querySearchParams.append(key, value.toString())
      }
    }

    setSelectedFilter(false)

    if (onSubmit && window.location.href.includes(selectedPath)) {
      onSubmit(newParams)
      return
    }

    const paramString = querySearchParams.toString()
    const path = `${redirectUrl}${selectedPath}`

    setInnerLoading(true)
    window.location.href = paramString ? `${path}?${paramString}` : path
  }

  const handleResetFilters = () => {
    setAgeCategoryCounts({})
    setCalendarRange(undefined)
  }
  return {
    updateGuestsCount,
    handleSelectedFilter,
    handleSubmit,
    handleResetFilters,
  }
}
