import { useEffect, useState } from 'react'

export default function useFilters(initialState, key?: any) {
  const [filters, setFilters] = useState(initialState)
  const [filtersApplied, setFiltersApplied] = useState(false)

  useEffect(() => {
    const prevFilters = getSessionFilters()
    setFilters({
      ...filters,
      ...prevFilters,
    })
  }, [])

  function onFilterChange(modified) {
    setFilters((prev) => ({
      ...prev,
      ...modified,
    }))

    const filterData = {
      ...filters,
      ...modified,
    }

    const sessionData = Object.keys(filterData).map((item, key) => {
      if (filtersCheck(item, filterData)) {
        return { key: item, value: filterData[item] }
      }
    })

    const filteredSessionArray = sessionData.filter(
      (value) => value !== undefined,
    )

    if (filteredSessionArray?.length > 0) {
      sessionStorage.setItem(key, JSON.stringify(filteredSessionArray))
      setFiltersApplied(true)
    } else {
      sessionStorage.removeItem(key)
      setFiltersApplied(false)
    }
  }

  function filtersCheck(item: any, filterData: any) {
    switch (true) {
      case !!filterData[item] &&
        item !== 'limit' &&
        item !== 'offset' &&
        item !== 'search' &&
        item !== 'page':
        return true
      default:
        return false
    }
  }

  function clearFilters() {
    setFilters(initialState)
    setFiltersApplied(false)
    sessionStorage.removeItem(key)
  }

  const getSessionFilters = () => {
    try {
      if (sessionStorage.getItem(key)) {
        setFiltersApplied(true)
        const parsed = JSON.parse(sessionStorage.getItem(key))
        const filters = parsed?.reduce(
          (acc, curr) => ({ ...acc, [curr.key]: curr.value }),
          {},
        )
        return filters
      }
    } catch (error) {}
  }

  return {
    filters,
    onFilterChange,
    clearFilters,
    filtersApplied,
  }
}
