import { useCallback, useMemo } from 'react'

import isObject from 'lodash/isObject'

import { SportTypes } from 'config'

import { useLocalStore } from 'hooks'

import type {
  SettingsBySport,
  Settings,
  SelectedActions,
  EpisodeDuration,
} from '../../types'
import { PlayerPlaylistFormats, defaultSettings } from '../../types'

const selectedActionsKey = 'playlist_settings'
const validator = (value: unknown) => Boolean(value) && isObject(value)

export const useSettingsState = (sportType?: SportTypes) => {
  const [settingsObj, setSettingsObj] = useLocalStore<SettingsBySport>({
    defaultValue: {},
    key: selectedActionsKey,
    validator,
  })

  /**
   * Сетит настройки определенного вида спорта,
   * работает как setState классовых компонентов,
   * то что передается в сеттер мержит со стейтом
  */
  const setSettings = useCallback((newSettings: Partial<Settings>) => {
    if (!sportType) return
    setSettingsObj((state) => {
      const oldSettings = state[sportType] || defaultSettings
      return {
        ...state,
        [sportType]: { ...oldSettings, ...newSettings },
      }
    })
  }, [sportType, setSettingsObj])

  const getSettings = useCallback(() => {
    if (!sportType) return defaultSettings
    return settingsObj[sportType] || defaultSettings
  }, [settingsObj, sportType])

  const setSelectedPlaylistFormat = useCallback(
    (value: PlayerPlaylistFormats) => setSettings({ selectedFormat: value }),
    [setSettings],
  )

  const setSelectedActions = useCallback(
    (value: SelectedActions) => setSettings({ selectedActions: value }),
    [setSettings],
  )

  const setEpisodeDuration = useCallback(
    (value: EpisodeDuration) => setSettings({ episodeDuration: value }),
    [setSettings],
  )

  const settings = useMemo(getSettings, [getSettings])

  return {
    setEpisodeDuration,
    setSelectedActions,
    setSelectedPlaylistFormat,
    setSettings,
    settings,
  }
}
