'use client'

import { useListDrawer } from '@payloadcms/ui/elements/ListDrawer'
import { useTranslation } from '@payloadcms/ui/providers/Translation'
import React, { Fragment, useCallback, useEffect, useState } from 'react'
import { ReactEditor, useSlate } from 'slate-react'

import { RelationshipIcon } from '../../../icons/Relationship/index.js'
import { ElementButton } from '../../Button.js'
import { EnabledRelationshipsCondition } from '../../EnabledRelationshipsCondition.js'
import { injectVoidElement } from '../../injectVoid.js'
import './index.scss'

const baseClass = 'relationship-rich-text-button'

const insertRelationship = (editor, { relationTo, value }) => {
  const text = { text: ' ' }

  const relationship = {
    type: 'relationship',
    children: [text],
    relationTo,
    value,
  }

  injectVoidElement(editor, relationship)

  ReactEditor.focus(editor)
}

type Props = {
  enabledCollectionSlugs: string[]
  path: string
}
const RelationshipButton: React.FC<Props> = ({ enabledCollectionSlugs }) => {
  const { t } = useTranslation()
  const editor = useSlate()
  const [selectedCollectionSlug, setSelectedCollectionSlug] = useState(
    () => enabledCollectionSlugs[0],
  )
  const [ListDrawer, ListDrawerToggler, { closeDrawer, isDrawerOpen }] = useListDrawer({
    collectionSlugs: enabledCollectionSlugs,
    selectedCollection: selectedCollectionSlug,
  })

  const onSelect = useCallback(
    ({ collectionSlug, docID }) => {
      insertRelationship(editor, {
        relationTo: collectionSlug,
        value: {
          id: docID,
        },
      })
      closeDrawer()
    },
    [editor, closeDrawer],
  )

  useEffect(() => {
    // always reset back to first option
    // TODO: this is not working, see the ListDrawer component
    setSelectedCollectionSlug(enabledCollectionSlugs[0])
  }, [isDrawerOpen, enabledCollectionSlugs])

  return (
    <Fragment>
      <ListDrawerToggler>
        <ElementButton
          className={baseClass}
          el="div"
          format="relationship"
          onClick={() => {
            // do nothing
          }}
          tooltip={t('fields:addRelationship')}
        >
          <RelationshipIcon />
        </ElementButton>
      </ListDrawerToggler>
      <ListDrawer onSelect={onSelect} />
    </Fragment>
  )
}

export const Button = (props: Props): React.ReactNode => {
  return (
    <EnabledRelationshipsCondition {...props}>
      <RelationshipButton {...props} />
    </EnabledRelationshipsCondition>
  )
}
