import type { MouseEvent, FocusEvent } from 'react'
import { useEffect, useState } from 'react'

import map from 'lodash/map'

import { FavoritesActions } from 'requests'

import { Modal } from 'features/Modal'
import { ProfileLink } from 'features/ProfileLink'
import { Close } from '../../libs/objects/Close'

import { TooltipBlock } from './TooltipBlock'
import { useUserFavoritesStore } from './store'
import {
  UserSportFavItemLogoWrapper,
  UserSportFavXWrapper,
  UserSportFavImgWrapper,
  UserSportFavStar,
  UserSportFavWrapper,
  ExclamationSign,
  FavoriteModal,
  Text,
  ScrollWrapper,
} from './styled'

type Props = {
  marginTop?: number,
}

export const UserFavorites = ({ marginTop }: Props) => {
  const {
    addRemoveFavorite,
    close,
    fetchFavorites,
    isOpen,
    userFavorites,
  } = useUserFavoritesStore()

  const [position, setPosition] = useState(0)

  useEffect(fetchFavorites, [fetchFavorites])

  const getPosition = (event: MouseEvent<HTMLDivElement> | FocusEvent<HTMLDivElement>) => {
    if (event.currentTarget) {
      setPosition(event.currentTarget.getBoundingClientRect().top)
    }
  }

  return (
    <UserSportFavWrapper>
      <UserSportFavStar marginTop={marginTop} />
      <ScrollWrapper>
        {
          map(userFavorites, (item) => (
            <UserSportFavItemLogoWrapper
              onFocus={getPosition}
              onMouseOver={getPosition}
              key={`${item.type}_${item.sport}_${item.id}`}
            >
              <UserSportFavXWrapper
                onClick={() => addRemoveFavorite({
                  action: FavoritesActions.REMOVE,
                  id: item.id,
                  sport: item.sport,
                  type: item.type,
                })}
              >
                <Close size={8} />
              </UserSportFavXWrapper>
              <TooltipBlock
                topPosition={position}
                favorite={item}
              />
              <ProfileLink
                id={item.id}
                sportType={item.sport}
                profileType={item.type}
              >
                <UserSportFavImgWrapper
                  id={item.id}
                  altNameObj={item}
                  sportType={item.sport}
                  profileType={item.type}
                />
              </ProfileLink>
            </UserSportFavItemLogoWrapper>
          ))
        }
      </ScrollWrapper>
      <Modal
        isOpen={isOpen}
        close={close}
      >
        <FavoriteModal>
          <ExclamationSign />
          <Text t='add_to_favorites_error' />
        </FavoriteModal>
      </Modal>
    </UserSportFavWrapper>
  )
}
