'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, File, formatDrawerSlug, useConfig, useEditDepth, 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, useId, useReducer, useRef, useState } from 'react';
import { useEditorConfigContext } from '../../../../lexical/config/client/EditorConfigProvider.js';
import { FieldsDrawer } from '../../../../utilities/fieldsDrawer/Drawer.js';
import { useLexicalDocumentDrawer } from '../../../../utilities/fieldsDrawer/useLexicalDocumentDrawer.js';
import { useLexicalDrawer } from '../../../../utilities/fieldsDrawer/useLexicalDrawer.js';
import { EnabledRelationshipsCondition } from '../../../relationship/client/utils/EnabledRelationshipsCondition.js';
import { INSERT_UPLOAD_WITH_DRAWER_COMMAND } from '../drawer/commands.js';
import { $isUploadNode } from '../nodes/UploadNode.js';
const baseClass = 'lexical-upload';
const initialParams = {
  depth: 0
};
const Component = props => {
  const {
    data: {
      fields,
      relationTo,
      value
    },
    nodeKey
  } = props;
  if (typeof value === 'object') {
    throw new Error('Upload value should be a string or number. The Lexical Upload component should not receive the populated value object.');
  }
  const {
    config: {
      collections,
      routes: {
        api
      },
      serverURL
    }
  } = useConfig();
  const uploadRef = useRef(null);
  const {
    uuid
  } = useEditorConfigContext();
  const editDepth = useEditDepth();
  const [editor] = useLexicalComposerContext();
  const [isSelected, setSelected, clearSelection] = useLexicalNodeSelection(nodeKey);
  const {
    editorConfig,
    fieldProps: {
      readOnly,
      schemaPath
    }
  } = useEditorConfigContext();
  const {
    i18n,
    t
  } = useTranslation();
  const [cacheBust, dispatchCacheBust] = useReducer(state => state + 1, 0);
  const [relatedCollection] = useState(() => collections.find(coll => coll.slug === relationTo));
  const componentID = useId();
  const extraFieldsDrawerSlug = formatDrawerSlug({
    slug: `lexical-upload-drawer-` + uuid + componentID,
    depth: editDepth
  });
  // Need to use hook to initialize useEffect that restores cursor position
  const {
    toggleDrawer
  } = useLexicalDrawer(extraFieldsDrawerSlug, true);
  const {
    closeDocumentDrawer,
    DocumentDrawer,
    DocumentDrawerToggler
  } = useLexicalDocumentDrawer({
    id: value,
    collectionSlug: relatedCollection.slug
  });
  // Get the referenced document
  const [{
    data
  }, {
    setParams
  }] = usePayloadAPI(`${serverURL}${api}/${relatedCollection.slug}/${value}`, {
    initialParams
  });
  const thumbnailSRC = data?.thumbnailURL || data?.url;
  const removeUpload = useCallback(() => {
    editor.update(() => {
      $getNodeByKey(nodeKey)?.remove();
    });
  }, [editor, nodeKey]);
  const updateUpload = useCallback(data_0 => {
    setParams({
      ...initialParams,
      cacheBust
    });
    dispatchCacheBust();
    closeDocumentDrawer();
  }, [setParams, cacheBust, closeDocumentDrawer]);
  const $onDelete = useCallback(event => {
    const deleteSelection = $getSelection();
    if (isSelected && $isNodeSelection(deleteSelection)) {
      event.preventDefault();
      editor.update(() => {
        deleteSelection.getNodes().forEach(node => {
          if ($isUploadNode(node)) {
            node.remove();
          }
        });
      });
    }
    return false;
  }, [editor, isSelected]);
  useEffect(() => {
    return mergeRegister(editor.registerCommand(CLICK_COMMAND, event_0 => {
      // Check if uploadRef.target or anything WITHIN uploadRef.target was clicked
      if (event_0.target === uploadRef.current || uploadRef.current?.contains(event_0.target)) {
        if (event_0.shiftKey) {
          setSelected(!isSelected);
        } else {
          if (!isSelected) {
            clearSelection();
            setSelected(true);
          }
        }
        return true;
      }
      return false;
    }, 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]);
  const hasExtraFields = editorConfig?.resolvedFeatureMap?.get('upload')?.sanitizedClientFeatureProps.collections?.[relatedCollection.slug]?.hasExtraFields;
  const onExtraFieldsDrawerSubmit = useCallback((_, data_1) => {
    // Update lexical node (with key nodeKey) with new data
    editor.update(() => {
      const uploadNode = $getNodeByKey(nodeKey);
      if (uploadNode) {
        const newData = {
          ...uploadNode.getData(),
          fields: data_1
        };
        uploadNode.setData(newData);
      }
    });
  }, [editor, nodeKey]);
  return /*#__PURE__*/_jsxs("div", {
    className: [baseClass, isSelected && `${baseClass}--selected`].filter(Boolean).join(' '),
    contentEditable: false,
    ref: uploadRef,
    children: [/*#__PURE__*/_jsxs("div", {
      className: `${baseClass}__card`,
      children: [/*#__PURE__*/_jsxs("div", {
        className: `${baseClass}__topRow`,
        children: [/*#__PURE__*/_jsx("div", {
          className: `${baseClass}__thumbnail`,
          children: thumbnailSRC ? /*#__PURE__*/_jsx("img", {
            alt: data?.filename,
            "data-lexical-upload-id": value,
            "data-lexical-upload-relation-to": relationTo,
            src: thumbnailSRC
          }) : /*#__PURE__*/_jsx(File, {})
        }), /*#__PURE__*/_jsxs("div", {
          className: `${baseClass}__topRowRightPanel`,
          children: [/*#__PURE__*/_jsx("div", {
            className: `${baseClass}__collectionLabel`,
            children: getTranslation(relatedCollection.labels.singular, i18n)
          }), editor.isEditable() && /*#__PURE__*/_jsxs("div", {
            className: `${baseClass}__actions`,
            children: [hasExtraFields ? /*#__PURE__*/_jsx(Button, {
              buttonStyle: "icon-label",
              className: `${baseClass}__upload-drawer-toggler`,
              disabled: readOnly,
              el: "button",
              icon: "edit",
              onClick: () => {
                toggleDrawer();
              },
              round: true,
              tooltip: t('fields:editRelationship')
            }) : null, /*#__PURE__*/_jsx(Button, {
              buttonStyle: "icon-label",
              className: `${baseClass}__swap-drawer-toggler`,
              disabled: readOnly,
              el: "button",
              icon: "swap",
              onClick: () => {
                editor.dispatchCommand(INSERT_UPLOAD_WITH_DRAWER_COMMAND, {
                  replace: {
                    nodeKey
                  }
                });
              },
              round: true,
              tooltip: t('fields:swapUpload')
            }), /*#__PURE__*/_jsx(Button, {
              buttonStyle: "icon-label",
              className: `${baseClass}__removeButton`,
              disabled: readOnly,
              icon: "x",
              onClick: e => {
                e.preventDefault();
                removeUpload();
              },
              round: true,
              tooltip: t('fields:removeUpload')
            })]
          })]
        })]
      }), /*#__PURE__*/_jsx("div", {
        className: `${baseClass}__bottomRow`,
        children: /*#__PURE__*/_jsx(DocumentDrawerToggler, {
          className: `${baseClass}__doc-drawer-toggler`,
          children: /*#__PURE__*/_jsx("strong", {
            children: data?.filename
          })
        })
      })]
    }), value ? /*#__PURE__*/_jsx(DocumentDrawer, {
      onSave: updateUpload
    }) : null, hasExtraFields ? /*#__PURE__*/_jsx(FieldsDrawer, {
      data: fields,
      drawerSlug: extraFieldsDrawerSlug,
      drawerTitle: t('general:editLabel', {
        label: getTranslation(relatedCollection.labels.singular, i18n)
      }),
      featureKey: "upload",
      handleDrawerSubmit: onExtraFieldsDrawerSubmit,
      schemaPath: schemaPath,
      schemaPathSuffix: relatedCollection.slug
    }) : null]
  });
};
export const UploadComponent = props => {
  return /*#__PURE__*/_jsx(EnabledRelationshipsCondition, {
    ...props,
    uploads: true,
    children: /*#__PURE__*/_jsx(Component, {
      ...props
    })
  });
};
//# sourceMappingURL=index.js.map