import React, { useEffect, useRef } from 'react'

let emojiMartRegistrationPromise = null

function ensureEmojiMartRegistered() {
  if (!emojiMartRegistrationPromise) {
    emojiMartRegistrationPromise = import('emoji-mart')
  }

  return emojiMartRegistrationPromise
}

function applyPickerProps(element, props) {
  if (!element) {
    return
  }

  element.data = props.data
  element.onEmojiSelect = props.onEmojiSelect
  element.theme = props.theme
  element.previewPosition = props.previewPosition
  element.skinTonePosition = props.skinTonePosition
  element.maxFrequentRows = props.maxFrequentRows
  element.perLine = props.perLine
  element.navPosition = props.navPosition
  element.set = props.set
  element.locale = props.locale
  element.autoFocus = props.autoFocus
  element.searchPosition = props.searchPosition
  element.dynamicWidth = props.dynamicWidth
  element.noCountryFlags = props.noCountryFlags
}

export default function EmojiMartPicker({
  data,
  onEmojiSelect,
  theme = 'auto',
  previewPosition = 'bottom',
  skinTonePosition = 'preview',
  maxFrequentRows = 4,
  perLine = 9,
  navPosition = 'top',
  set = 'native',
  locale = 'en',
  autoFocus = false,
  searchPosition,
  dynamicWidth,
  noCountryFlags,
  className = '',
}) {
  const hostRef = useRef(null)
  const pickerRef = useRef(null)

  useEffect(() => {
    let cancelled = false

    ensureEmojiMartRegistered().then(() => {
      if (cancelled || !hostRef.current) {
        return
      }

      if (!pickerRef.current) {
        pickerRef.current = document.createElement('em-emoji-picker')
        hostRef.current.replaceChildren(pickerRef.current)
      }

      applyPickerProps(pickerRef.current, {
        data,
        onEmojiSelect,
        theme,
        previewPosition,
        skinTonePosition,
        maxFrequentRows,
        perLine,
        navPosition,
        set,
        locale,
        autoFocus,
        searchPosition,
        dynamicWidth,
        noCountryFlags,
      })
    })

    return () => {
      cancelled = true
    }
  }, [
    data,
    onEmojiSelect,
    theme,
    previewPosition,
    skinTonePosition,
    maxFrequentRows,
    perLine,
    navPosition,
    set,
    locale,
    autoFocus,
    searchPosition,
    dynamicWidth,
    noCountryFlags,
  ])

  useEffect(() => {
    return () => {
      if (hostRef.current) {
        hostRef.current.replaceChildren()
      }

      pickerRef.current = null
    }
  }, [])

  return <div ref={hostRef} className={className} />
}