'use client'

import classNames from 'classnames'
import { createRef, FC, HTMLAttributes, ReactNode, useCallback, useState } from 'react'
import type { TMessageboxSkin } from 'shared-types'

import { PktIcon } from '..'

export type { TMessageboxSkin }

export interface IPktMessagebox extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
  skin?: TMessageboxSkin
  title?: ReactNode
  compact?: boolean
  closable?: boolean
  onClose?: () => void
}

export const PktMessagebox: FC<IPktMessagebox> = ({
  children,
  className,
  skin,
  title,
  compact,
  closable,
  onClose,
  ...props
}: IPktMessagebox) => {
  const [closed, setClosed] = useState(false)

  const classes = {
    'pkt-messagebox': true,
    'pkt-messagebox--compact': compact,
    [`pkt-messagebox--${skin}`]: skin,
    'pkt-messagebox--closable': closable,
    'pkt-hide': closed,
  }

  const componentRootRef = createRef<HTMLDivElement>()

  const close = useCallback(() => {
    setClosed(true)
    if (onClose) {
      onClose()
    }
  }, [setClosed, onClose])

  return (
    <div {...props} className={classNames(classes, className)} ref={componentRootRef}>
      {closable && (
        <div className={'pkt-messagebox__close'}>
          <button
            onClick={close}
            className={'pkt-btn pkt-btn--tertiary pkt-btn--small pkt-btn--icon-only'}
            aria-label={'Lukk'}
          >
            <PktIcon name="close" className="pkt-link__icon" />
          </button>
        </div>
      )}
      {title && <div className="pkt-messagebox__title">{title}</div>}
      <div className={'pkt-messagebox__text'}>{children}</div>
    </div>
  )
}

PktMessagebox.displayName = 'PktMessagebox'
