'use client';

import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext.js';
import { useLexicalNodeSelection } from '@lexical/react/useLexicalNodeSelection.js';
import { mergeRegister } from '@lexical/utils';
import { getTranslation } from '@payloadcms/translations';
import { Button, useConfig, usePayloadAPI, useTranslation } from '@payloadcms/ui';
import { $getNodeByKey, $getSelection, $isNodeSelection, CLICK_COMMAND, COMMAND_PRIORITY_LOW, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND } from 'lexical';
import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react';
import { useEditorConfigContext } from '../../../../lexical/config/client/EditorConfigProvider.js';
import { useLexicalDocumentDrawer } from '../../../../utilities/fieldsDrawer/useLexicalDocumentDrawer.js';
import { INSERT_RELATIONSHIP_WITH_DRAWER_COMMAND } from '../drawer/commands.js';
import { $isRelationshipNode } from '../nodes/RelationshipNode.js';
const baseClass = 'lexical-relationship';
const initialParams = {
  depth: 0
};
const Component = props => {
  const {
    data: {
      relationTo,
      value
    },
    nodeKey
  } = props;
  if (typeof value === 'object') {
    throw new Error('Relationship value should be a string or number. The Lexical Relationship component should not receive the populated value object.');
  }
  const relationshipElemRef = useRef(null);
  const [editor] = useLexicalComposerContext();
  const [isSelected, setSelected, clearSelection] = useLexicalNodeSelection(nodeKey);
  const {
    fieldProps: {
      readOnly
    }
  } = useEditorConfigContext();
  const {
    config: {
      collections,
      routes: {
        api
      },
      serverURL
    }
  } = useConfig();
  const [relatedCollection, setRelatedCollection] = useState(() => collections.find(coll => coll.slug === relationTo));
  const {
    i18n,
    t
  } = useTranslation();
  const [cacheBust, dispatchCacheBust] = useReducer(state => state + 1, 0);
  const [{
    data
  }, {
    setParams
  }] = usePayloadAPI(`${serverURL}${api}/${relatedCollection.slug}/${value}`, {
    initialParams
  });
  const {
    closeDocumentDrawer,
    DocumentDrawer,
    DocumentDrawerToggler
  } = useLexicalDocumentDrawer({
    id: value,
    collectionSlug: relatedCollection.slug
  });
  const removeRelationship = useCallback(() => {
    editor.update(() => {
      $getNodeByKey(nodeKey)?.remove();
    });
  }, [editor, nodeKey]);
  const updateRelationship = React.useCallback(() => {
    setParams({
      ...initialParams,
      cacheBust
    });
    closeDocumentDrawer();
    dispatchCacheBust();
  }, [cacheBust, setParams, closeDocumentDrawer]);
  const $onDelete = useCallback(payload => {
    const deleteSelection = $getSelection();
    if (isSelected && $isNodeSelection(deleteSelection)) {
      const event = payload;
      event.preventDefault();
      editor.update(() => {
        deleteSelection.getNodes().forEach(node => {
          if ($isRelationshipNode(node)) {
            node.remove();
          }
        });
      });
    }
    return false;
  }, [editor, isSelected]);
  const onClick = useCallback(payload_0 => {
    const event_0 = payload_0;
    // Check if relationshipElemRef.target or anything WITHIN relationshipElemRef.target was clicked
    if (event_0.target === relationshipElemRef.current || relationshipElemRef.current?.contains(event_0.target)) {
      if (event_0.shiftKey) {
        setSelected(!isSelected);
      } else {
        if (!isSelected) {
          clearSelection();
          setSelected(true);
        }
      }
      return true;
    }
    return false;
  }, [isSelected, setSelected, clearSelection]);
  useEffect(() => {
    return mergeRegister(editor.registerCommand(CLICK_COMMAND, onClick, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_DELETE_COMMAND, $onDelete, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_BACKSPACE_COMMAND, $onDelete, COMMAND_PRIORITY_LOW));
  }, [clearSelection, editor, isSelected, nodeKey, $onDelete, setSelected, onClick]);
  return /*#__PURE__*/_jsxs("div", {
    className: [baseClass, isSelected && `${baseClass}--selected`].filter(Boolean).join(' '),
    contentEditable: false,
    ref: relationshipElemRef,
    children: [/*#__PURE__*/_jsxs("div", {
      className: `${baseClass}__wrap`,
      children: [/*#__PURE__*/_jsx("p", {
        className: `${baseClass}__label`,
        children: t('fields:labelRelationship', {
          label: relatedCollection.labels?.singular ? getTranslation(relatedCollection.labels?.singular, i18n) : relatedCollection.slug
        })
      }), /*#__PURE__*/_jsx(DocumentDrawerToggler, {
        className: `${baseClass}__doc-drawer-toggler`,
        children: /*#__PURE__*/_jsx("p", {
          className: `${baseClass}__title`,
          children: data ? data[relatedCollection?.admin?.useAsTitle || 'id'] : value
        })
      })]
    }), editor.isEditable() && /*#__PURE__*/_jsxs("div", {
      className: `${baseClass}__actions`,
      children: [/*#__PURE__*/_jsx(Button, {
        buttonStyle: "icon-label",
        className: `${baseClass}__swapButton`,
        disabled: readOnly,
        el: "button",
        icon: "swap",
        onClick: () => {
          if (nodeKey) {
            editor.dispatchCommand(INSERT_RELATIONSHIP_WITH_DRAWER_COMMAND, {
              replace: {
                nodeKey
              }
            });
          }
        },
        round: true,
        tooltip: t('fields:swapRelationship')
      }), /*#__PURE__*/_jsx(Button, {
        buttonStyle: "icon-label",
        className: `${baseClass}__removeButton`,
        disabled: readOnly,
        icon: "x",
        onClick: e => {
          e.preventDefault();
          removeRelationship();
        },
        round: true,
        tooltip: t('fields:removeRelationship')
      })]
    }), !!value && /*#__PURE__*/_jsx(DocumentDrawer, {
      onSave: updateRelationship
    })]
  });
};
export const RelationshipComponent = props => {
  return /*#__PURE__*/_jsx(Component, {
    ...props
  });
};
//# sourceMappingURL=RelationshipComponent.js.map