import { Button, Colors } from '@blueprintjs/core'
import { Dot } from '@blueprintjs/icons'
import type { RefObject } from 'react'
import { useCallback, useEffect, useMemo, useState, type FC } from 'react'

const isVisible = (element: HTMLElement) => {
  const { top, bottom } = element.getBoundingClientRect()
  return top >= 0 && bottom <= window.innerHeight
}

interface SeeAllUnreadButtonProps {
  firstUnreadId: string | undefined
  unreadLogsStartRef: RefObject<HTMLDivElement | null>
}

const SeeAllUnreadButton: FC<SeeAllUnreadButtonProps> = ({
  firstUnreadId,
  unreadLogsStartRef,
}) => {
  // TODO: disable when the scroll won't do anything
  const disabled = useMemo(() => firstUnreadId === undefined, [firstUnreadId])

  // TODO: does not reset when changing the team
  const [highlighted, setHighlighted] = useState(
    !!unreadLogsStartRef.current && !isVisible(unreadLogsStartRef.current)
  )
  useEffect(() => {
    setHighlighted(
      !!unreadLogsStartRef.current && !isVisible(unreadLogsStartRef.current)
    )
  }, [unreadLogsStartRef])

  const handleClick = useCallback(() => {
    if (unreadLogsStartRef.current) {
      unreadLogsStartRef.current.scrollIntoView({ behavior: 'smooth' })
    }
    setHighlighted(false)
  }, [unreadLogsStartRef])

  return (
    <Button
      icon='arrow-up'
      minimal
      onClick={handleClick}
      rightIcon={highlighted ? <Dot color={Colors.RED3} /> : undefined}
      disabled={disabled}
      title={disabled ? 'No unread logs' : undefined}
      intent={highlighted ? 'warning' : undefined}
    >
      {highlighted ? <b>See all unread</b> : 'See all unread'}
    </Button>
  )
}

export default SeeAllUnreadButton
