import { Alert } from '@tidbcloud/uikit'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import DOMPurify from 'dompurify'
import React, { useEffect, useState, useRef } from 'react'

interface IProps {
  message: string
  onDismiss?: () => void
  style?: React.CSSProperties
  autoScroll?: boolean // auto scroll to view
  closable?: boolean
}

// see https://github.com/cure53/DOMPurify/issues/317#issuecomment-912474068
const TEMPORARY_ATTRIBUTE = 'data-temp-href-target'

DOMPurify.addHook('beforeSanitizeAttributes', function (node) {
  if (node.tagName === 'A') {
    if (!node.hasAttribute('target')) {
      node.setAttribute('target', '_self')
    }

    if (node.hasAttribute('target')) {
      node.setAttribute(TEMPORARY_ATTRIBUTE, node.getAttribute('target') || '')
    }
  }
})

DOMPurify.addHook('afterSanitizeAttributes', function (node) {
  if (node.tagName === 'A' && node.hasAttribute(TEMPORARY_ATTRIBUTE)) {
    node.setAttribute('target', node.getAttribute(TEMPORARY_ATTRIBUTE) || '')
    node.removeAttribute(TEMPORARY_ATTRIBUTE)
    if (node.getAttribute('target') === '_blank') {
      node.setAttribute('rel', 'noopener noreferrer')
    }
  }
})

export default function FormErrorMessage({ message, onDismiss, autoScroll, closable = false, style }: IProps) {
  const bottomRef = useRef<HTMLDivElement>(null)
  const [show, setShow] = useState(true)

  useEffect(() => {
    if (!autoScroll) return
    // 👇️ scroll to bottom every time messages change
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [autoScroll, message])

  useEffect(() => {
    setShow(true)
  }, [message])

  if (!message || !show) {
    return null
  }

  return (
    <Alert
      withCloseButton={Boolean(onDismiss) || closable}
      color="red"
      icon={<IconAlertCircle />}
      onClose={() => {
        setShow(false)
        onDismiss?.()
      }}
      style={style}
    >
      {/* trick for displaying error message with html tags like <a></a> */}
      <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(message) }} />
      <div ref={bottomRef} />
    </Alert>
  )
}
