import {
  useCallback,
  useState,
  useMemo,
} from 'react'

import isEmpty from 'lodash/isEmpty'
import isNull from 'lodash/isNull'
import size from 'lodash/size'
import xorWith from 'lodash/xorWith'
import isEqual from 'lodash/isEqual'

import type{ UserPreferences } from 'requests/getUserPreferences'
import { getUserPreferences as getUserPreferencesRequest } from 'requests/getUserPreferences'
import { saveUserPreferences as saveUserPreferencesRequest } from 'requests/saveUserPreferences'

import { useRequest } from 'hooks'

export const usePreferencesLoader = (
  selectedTournaments: UserPreferences,
  onApply: () => void,
) => {
  const [userPreferences, setUserPreferences] = useState<UserPreferences | null>(null)

  const {
    isFetching,
    request: fetchUserPreferences,
  } = useRequest(getUserPreferencesRequest)
  const {
    isFetching: isSaving,
    request: saveUserPreferences,
  } = useRequest(saveUserPreferencesRequest)

  const fetchInitialPreferences = useCallback(() => {
    if (isNull(userPreferences)) {
      fetchUserPreferences().then(setUserPreferences)
    }
  }, [fetchUserPreferences, userPreferences])

  const onApplyClick = () => {
    const data = isEmpty(selectedTournaments) ? null : selectedTournaments
    saveUserPreferences(data)
      .then(fetchUserPreferences)
      .then(setUserPreferences)
      .then(onApply)
  }

  const isApplyButtonDisabled = useMemo(() => {
    if (!userPreferences) return true

    if (size(userPreferences) !== size(selectedTournaments)) return false

    return isEmpty(xorWith(
      userPreferences,
      selectedTournaments,
      isEqual,
    ))
  }, [selectedTournaments, userPreferences])

  return {
    fetchInitialPreferences,
    isApplyButtonDisabled,
    isFetching,
    isSaving,
    onApplyClick,
    userPreferences,
  }
}
