import * as React from 'react'
import Cookie from 'js-cookie'

export type ChildrenProps = Readonly<{
  name: string
}>

export type Props = Readonly<{
  name: string
  className?: string
  hasCloseButton: boolean
  children: (props: ChildrenProps) => React.ReactNode
}>

export type State = Readonly<{
  bannerHasBeenClosed: boolean
}>

export default class Banner extends React.Component<Props, State> {
  readonly state: State

  constructor(props: Props) {
    super(props)
    this.state = {
      bannerHasBeenClosed: Cookie.get(`${props.name}--is-closed`),
    }
  }

  closeBanner = () => {
    Cookie.set(`${this.props.name}--is-closed`, true, { expires: 365 })
    this.setState({ bannerHasBeenClosed: true })
  }

  render() {
    const { name, className, hasCloseButton, children } = this.props

    return !this.state.bannerHasBeenClosed ? (
      <section
        id={name}
        className={`ui-banner ui-banner--${name} ${className}`}
      >
        <header className={`ui-banner__header ui-banner__header--${name}`}>
          {children({ name })}

          {hasCloseButton && (
            <div
              className={`ui-banner__close-button-container ui-banner__close-button-container--${name}`}
            >
              <button
                id={`${name}-button`}
                onClick={this.closeBanner}
                className={`ui-banner__close-button ui-banner__close-button--${name} ui-p--1`}
              >
                <span
                  className={`ui-banner__close-icon ui-banner__close-icon--${name} ui-icon--close ui-text__h6`}
                />
              </button>
            </div>
          )}
        </header>
      </section>
    ) : null
  }
}
