import type { Intent } from '@blueprintjs/core'
import { Button, NonIdealState } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Placement } from '@floating-ui/react'
import type { FC } from 'react'
import { useContext, useEffect, useState } from 'react'
import usePopoverElement from '../popover/usePopoverElement'
import Notification from './components/Notification'
import NotificationListContext from './contexts/NotificationListContext'
import { useNotifyContext } from './contexts/NotifyContext'

interface NotificationDropdownProps {
  hideLabel?: boolean
  placement?: Placement
  fill?: boolean
}

const notificationBox = css`
  min-width: 28rem;
  max-width: 28rem;
  overflow: auto;
  display: grid;
  grid-template-rows: 1fr auto;
  gap: 0.5rem;
`

const notifications = css`
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  overflow: auto;
`

const NotificationDropdown: FC<NotificationDropdownProps> = ({
  hideLabel,
  placement = 'bottom',
  fill,
}) => {
  const value = useContext(NotificationListContext)
  const [open, setOpen] = useState<boolean>(false)
  const { clearNotify } = useNotifyContext()
  const { children, getReferenceProps, setReference } = usePopoverElement({
    open,
    setOpen,
    placement,
    children: (
      <div className={notificationBox}>
        <div className={notifications}>
          {value && value.length > 0 ? (
            value.map(x => <Notification key={x.timestamp} {...x} />)
          ) : (
            <NonIdealState
              icon='low-voltage-pole'
              title='No notifications'
              description='There are no notifications to display'
            />
          )}
        </div>
        <div>
          <Button
            fill
            intent='danger'
            icon='trash'
            onClick={() => clearNotify()}
          >
            Delete all
          </Button>
        </div>
      </div>
    ),
  })

  const count = value?.length ?? 0
  const intent: Intent = count > 0 ? 'warning' : 'none'
  useEffect(() => {
    if (count === 0) {
      setOpen(false)
    }
  }, [count])

  return (
    <>
      <Button
        ref={setReference}
        intent={intent}
        active={open}
        icon='notifications'
        alignText='left'
        fill={fill}
        minimal
        text={hideLabel ? undefined : 'Notifications'}
        title='Notifications'
        onClick={() => setOpen(prev => !prev)}
        {...getReferenceProps}
      />
      {children}
    </>
  )
}

export default NotificationDropdown
