'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 } from '../button/Button'
import { PktIcon } from '../icon/Icon'

export interface IPktAlert extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
  skin?: TAlertSkin
  closeAlert?: boolean
  title?: ReactNode
  date?: string
  ariaLive?: TAriaLive
  /**
   * @deprecated Bruk size i stedet. Uten eksplisitt size gir compact størrelsen 'small'.
   */
  compact?: boolean
  role?: TAlertRole
  /**
   * Størrelse på varslingen.
   *
   * @default medium
   */
  size?: 'medium' | 'small' | 'xsmall'
  onClose?: (e: CustomEvent) => void
}

export type { TAlertSkin }

export const PktAlert: FC<IPktAlert> = ({
  children,
  closeAlert,
  compact,
  size = compact ? 'small' : 'medium',
  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--${size}`]: size,
    [`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={size}
              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'
