import type { Intent } from '@blueprintjs/core'
import { Button, NonIdealState, NonIdealStateIconSize } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Placement } from '@floating-ui/react'
import type { FC } from 'react'
import { useEffect, useMemo, useState } from 'react'
import usePopoverElement from '../popover/usePopoverElement'
import Notification from './components/Notification'
import { clearNotify, useNotificationStorage } from './var/notifications'

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;
  padding-top: 1rem;
  flex-direction: column;
  gap: 0.25rem;
  overflow: auto;
`

const NotificationDropdown: FC<NotificationDropdownProps> = ({
  hideLabel,
  placement = 'bottom',
  fill,
}) => {
  const value = useNotificationStorage()
  const [open, setOpen] = useState<boolean>(false)
  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
              iconSize={NonIdealStateIconSize.SMALL}
              layout='horizontal'
              icon='low-voltage-pole'
              title='No notifications'
              description='There are no notifications to display'
            />
          )}
        </div>
        <div
          className={css`
            display: flex;
            justify-content: end;
            padding-top: 1rem;
          `}
        >
          <Button 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])

  const buttonChildren = useMemo(() => {
    if (hideLabel) {
      return undefined
    }
    if (count) {
      return <b>{`Notifications (${count})`}</b>
    }
    return 'Notifications'
  }, [count, hideLabel])

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

export default NotificationDropdown
