'use client'

import classNames from 'classnames'
import { FC, HTMLAttributes, ReactElement, ReactNode, useCallback, useState } from 'react'
import type { TAlertRole, TAlertSkin,TAriaLive } from 'shared-types'

import { PktButton, PktIcon } from '..'

export interface IPktAlert extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
  skin?: TAlertSkin
  closeAlert?: boolean
  title?: ReactNode
  date?: string
  ariaLive?: TAriaLive
  compact?: boolean
  role?: TAlertRole
  onClose?: (e: CustomEvent) => void
}

export type { TAlertSkin }

export const PktAlert: FC<IPktAlert> = ({
  children,
  closeAlert,
  compact,
  title,
  date,
  ariaLive: ariaLiveCamel,
  'aria-live': ariaLiveKebab = 'polite' as TAriaLive,
  role = 'status',
  skin = 'info' as TAlertSkin,
  className,
  ...props
}: IPktAlert): ReactElement => {
  const [isClosed, setIsClosed] = useState(false)

  const classes = {
    'pkt-alert': true,
    'pkt-alert--compact': compact,
    [`pkt-alert--${skin}`]: skin,
    'pkt-hide': isClosed,
  }
  const gridClasses = {
    'pkt-alert__grid': true,
    'pkt-alert__noTitle': !title,
    'pkt-alert__noDate': !date,
  }

  const onClose = useCallback(() => {
    setIsClosed(true)
    if (props.onClose) {
      props.onClose(new CustomEvent('close', { detail: { origin: event }, bubbles: true, composed: true }))
    }
  }, [props.onClose, setIsClosed])

  const ariaLive = ariaLiveCamel || ariaLiveKebab

  return (
    <div {...props} aria-live={ariaLive} role={role} className={classNames(classes, className)}>
      <div className={classNames(gridClasses)}>
        <PktIcon
          className="pkt-alert__icon"
          aria-hidden="true"
          name={skin === 'info' ? 'alert-information' : `alert-${skin}`}
        ></PktIcon>

        {closeAlert && (
          <div className="pkt-alert__close">
            <PktButton
              tabIndex={0}
              aria-label="close"
              size={compact ? 'small' : 'medium'}
              type="button"
              skin="tertiary"
              iconName="close"
              variant="icon-only"
              onClick={onClose}
            >
              <span className="sr-only">Lukk</span>
            </PktButton>
          </div>
        )}
        {title && <div className="pkt-alert__title">{title}</div>}

        <div className="pkt-alert__text">{children}</div>

        {date && <div className="pkt-alert__date">Sist oppdatert: {date}</div>}
      </div>
    </div>
  )
}

PktAlert.displayName = 'PktAlert'
