import { useEffect } from 'react'
import { useSetRecoilState } from 'recoil'

import { LIKES_API_URL } from 'config'

import { useAuthStore } from 'features/AuthStore'
import { FULL_MATCH_BOUNDARY } from 'features/MatchPage/components/LiveMatch/helpers'

import {
  usePageParams,
  useVideoBounds,
  useWebSocket,
} from 'hooks'

import {
  myLikesState,
  totalLikesState,
  type RawLikeEvent,
} from '../atoms'
import { useMatchPageStore } from '..'

interface Data {
  data: Array<RawLikeEvent>,
  type: 'user_likes' | 'total_likes',
}

export const useLikes = () => {
  const setTotalLikes = useSetRecoilState(totalLikesState)
  const setMyLikes = useSetRecoilState(myLikesState)

  const { playingProgress } = useMatchPageStore()

  const videoBounds = useVideoBounds()

  const { profileId, sportType } = usePageParams()
  const { user } = useAuthStore()

  useEffect(() => {
    setTotalLikes([])
    setMyLikes([])
  }, [setMyLikes, setTotalLikes, profileId, sportType])

  const url = `${LIKES_API_URL}?sport_id=${sportType}&match_id=${profileId}&access_token=${user?.access_token}`

  const { sendMessage, webSocketState } = useWebSocket<Data>({
    allowConnection: Boolean(user),
    autoReconnect: true,
    handlers: {
      onMessage: ({ data = [], type }) => {
        type === 'total_likes' && setTotalLikes(data)
        type === 'user_likes' && setMyLikes(data)
      },
    },
    maxReconnectAttempts: 10,
    url,
  })

  const likeClick = () => {
    const startSecond = Number(videoBounds?.find(({ h }) => h === FULL_MATCH_BOUNDARY)?.s || 0)

    const message = {
      data: {
        second: playingProgress + startSecond,
      },
      event: 'like',
    }

    sendMessage(message)
  }

  return {
    canLike: user && webSocketState === WebSocket.OPEN,
    likeClick,
  }
}
