import { useMemo, useState } from 'react'

import includes from 'lodash/includes'
import filter from 'lodash/filter'
import isEmpty from 'lodash/isEmpty'
import size from 'lodash/size'

type TTogglePlayers = {
  id: Number,
  team: String,
}

type TFilters = {
  events: Array<Number>,
  players: Array<Number>,
}

export const useFiltersPopup = () => {
  const [isOpen, setIsOpen] = useState(false)
  const [activeEvents, setActiveEvents] = useState<Array<Number>>([])
  const [activeFirstTeamPlayers, setActiveFirstTeamPlayers] = useState<Array<Number>>([])
  const [activeSecondTeamPlayers, setActiveSecondTeamPlayers] = useState<Array<Number>>([])
  const [activeFilters, setActiveFilters] = useState<TFilters>({ events: [], players: [] })

  const toggle = () => {
    setIsOpen(!isOpen)
  }

  const close = () => {
    setIsOpen(false)
  }

  const toggleActiveEvents = (id: number) => () => {
    setActiveEvents(includes(activeEvents, id)
      ? [...filter(activeEvents, (item) => item !== id)]
      : [...activeEvents, id])
  }

  const toggleActivePlayers = ({ id, team }: TTogglePlayers) => () => {
    const teamState = team === 'team1'
      ? activeFirstTeamPlayers
      : activeSecondTeamPlayers

    const setterTeamState = team === 'team1'
      ? setActiveFirstTeamPlayers
      : setActiveSecondTeamPlayers

    setterTeamState(includes(teamState, id)
      ? [...filter(teamState, (item) => item !== id)]
      : [...teamState, id])
  }

  const resetPlayers = (team: string) => () => {
    const teamState = team === 'team1'
      ? activeFirstTeamPlayers
      : activeSecondTeamPlayers

    const setterTeamState = team === 'team1'
      ? setActiveFirstTeamPlayers
      : setActiveSecondTeamPlayers

    if (isEmpty(teamState)) return
    setterTeamState([])
  }

  const resetEvents = () => {
    if (isEmpty(activeEvents)) return
    setActiveEvents([])
  }

  const applyFilters = () => {
    setActiveFilters({
      events: [...activeEvents],
      players: [...activeFirstTeamPlayers, ...activeSecondTeamPlayers],
    })
    close()
  }

  const isEmptyFilters = useMemo(() => (
    isEmpty(activeFilters.events) && isEmpty(activeFilters.players)), [activeFilters])

  const countOfFilters = useMemo(() => (
    size(activeFilters.events) + size(activeFilters.players)), [activeFilters])

  return {
    activeEvents,
    activeFirstTeamPlayers,
    activeSecondTeamPlayers,
    applyFilters,
    close,
    countOfFilters,
    filters: activeFilters,
    isEmptyFilters,
    isOpen,
    resetEvents,
    resetPlayers,
    toggle,
    toggleActiveEvents,
    toggleActivePlayers,
  }
}
