'use client';
import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
import { getTranslation } from '@payloadcms/translations';
import { hasAutosaveEnabled } from 'payload/shared';
import React, { Fragment, useCallback, useEffect, useState } from 'react';
import { useRelatedCollections } from '../../hooks/useRelatedCollections.js';
import { PlusIcon } from '../../icons/Plus/index.js';
import { useAuth } from '../../providers/Auth/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { Button } from '../Button/index.js';
import { useDocumentDrawer } from '../DocumentDrawer/index.js';
import { Popup } from '../Popup/index.js';
import * as PopupList from '../Popup/PopupButtonList/index.js';
import './index.scss';
import { Tooltip } from '../Tooltip/index.js';
const baseClass = 'relationship-add-new';
export const AddNewRelation = ({ Button: ButtonFromProps, hasMany, onChange, path, relationTo, unstyled, value })=>{
    const relatedCollections = useRelatedCollections(relationTo);
    const { permissions } = useAuth();
    const [show, setShow] = useState(false);
    const [selectedCollection, setSelectedCollection] = useState();
    const relatedToMany = relatedCollections.length > 1;
    const [collectionConfig, setCollectionConfig] = useState(()=>!relatedToMany ? relatedCollections[0] : undefined);
    const [popupOpen, setPopupOpen] = useState(false);
    const { i18n, t } = useTranslation();
    const [showTooltip, setShowTooltip] = useState(false);
    const [DocumentDrawer, DocumentDrawerToggler, { isDrawerOpen, toggleDrawer }] = useDocumentDrawer({
        collectionSlug: collectionConfig?.slug
    });
    const onSave = useCallback(({ doc, operation })=>{
        // if autosave is enabled, the operation will be 'update'
        if (operation === 'create' || operation === 'update' && hasAutosaveEnabled(collectionConfig)) {
            // ensure the value is not already in the array
            let isNewValue = false;
            if (!value) {
                isNewValue = true;
            } else {
                isNewValue = Array.isArray(value) ? !value.some((v)=>v && v.value === doc.id) : value.value !== doc.id;
            }
            if (isNewValue) {
                if (hasMany === true) {
                    onChange([
                        ...Array.isArray(value) ? value : [],
                        {
                            relationTo: collectionConfig?.slug,
                            value: doc.id
                        }
                    ]);
                } else {
                    onChange({
                        relationTo: collectionConfig?.slug,
                        value: doc.id
                    });
                }
            }
            setSelectedCollection(undefined);
        }
    }, [
        collectionConfig,
        hasMany,
        onChange,
        value
    ]);
    const onPopupToggle = useCallback((state)=>{
        setPopupOpen(state);
    }, []);
    useEffect(()=>{
        if (permissions) {
            if (relatedCollections.length === 1) {
                setShow(permissions.collections[relatedCollections[0]?.slug]?.create);
            } else {
                setShow(relatedCollections.some((collection)=>permissions.collections[collection?.slug]?.create));
            }
        }
    }, [
        permissions,
        relatedCollections
    ]);
    useEffect(()=>{
        if (relatedToMany && selectedCollection) {
            setCollectionConfig(relatedCollections.find((collection)=>collection?.slug === selectedCollection));
        }
    }, [
        selectedCollection,
        relatedToMany,
        relatedCollections
    ]);
    useEffect(()=>{
        if (relatedToMany && collectionConfig) {
            // the drawer must be rendered on the page before before opening it
            // this is why 'selectedCollection' is different from 'collectionConfig'
            toggleDrawer();
            setSelectedCollection(undefined);
        }
    }, [
        toggleDrawer,
        relatedToMany,
        collectionConfig
    ]);
    useEffect(()=>{
        if (relatedToMany && !isDrawerOpen) {
            setCollectionConfig(undefined);
        }
    }, [
        isDrawerOpen,
        relatedToMany
    ]);
    const label = t('fields:addNewLabel', {
        label: getTranslation(relatedCollections[0]?.labels.singular, i18n)
    });
    if (!show) {
        return null;
    }
    return /*#__PURE__*/ _jsxDEV("div", {
        className: baseClass,
        id: `${path}-add-new`,
        children: [
            relatedCollections.length === 1 && /*#__PURE__*/ _jsxDEV(Fragment, {
                children: [
                    /*#__PURE__*/ _jsxDEV(DocumentDrawerToggler, {
                        className: [
                            `${baseClass}__add-button`,
                            unstyled && `${baseClass}__add-button--unstyled`
                        ].filter(Boolean).join(' '),
                        onClick: ()=>{
                            setShowTooltip(false);
                        },
                        onMouseEnter: ()=>setShowTooltip(true),
                        onMouseLeave: ()=>setShowTooltip(false),
                        children: ButtonFromProps ? ButtonFromProps : /*#__PURE__*/ _jsxDEV(Fragment, {
                            children: [
                                /*#__PURE__*/ _jsxDEV(Tooltip, {
                                    className: `${baseClass}__tooltip`,
                                    show: showTooltip,
                                    children: label
                                }, void 0, false, {
                                    fileName: "src/elements/AddNewRelation/index.tsx",
                                    lineNumber: 164,
                                    columnNumber: 17
                                }, this),
                                /*#__PURE__*/ _jsxDEV(PlusIcon, {}, void 0, false, {
                                    fileName: "src/elements/AddNewRelation/index.tsx",
                                    lineNumber: 167,
                                    columnNumber: 17
                                }, this)
                            ]
                        }, void 0, true, {
                            fileName: "src/elements/AddNewRelation/index.tsx",
                            lineNumber: 163,
                            columnNumber: 15
                        }, this)
                    }, void 0, false, {
                        fileName: "src/elements/AddNewRelation/index.tsx",
                        lineNumber: 147,
                        columnNumber: 11
                    }, this),
                    /*#__PURE__*/ _jsxDEV(DocumentDrawer, {
                        onSave: onSave
                    }, void 0, false, {
                        fileName: "src/elements/AddNewRelation/index.tsx",
                        lineNumber: 171,
                        columnNumber: 11
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/elements/AddNewRelation/index.tsx",
                lineNumber: 146,
                columnNumber: 9
            }, this),
            relatedCollections.length > 1 && /*#__PURE__*/ _jsxDEV(Fragment, {
                children: [
                    /*#__PURE__*/ _jsxDEV(Popup, {
                        button: ButtonFromProps ? ButtonFromProps : /*#__PURE__*/ _jsxDEV(Button, {
                            buttonStyle: "none",
                            className: `${baseClass}__add-button`,
                            tooltip: popupOpen ? undefined : t('fields:addNew'),
                            children: /*#__PURE__*/ _jsxDEV(PlusIcon, {}, void 0, false, {
                                fileName: "src/elements/AddNewRelation/index.tsx",
                                lineNumber: 186,
                                columnNumber: 19
                            }, void 0)
                        }, void 0, false, {
                            fileName: "src/elements/AddNewRelation/index.tsx",
                            lineNumber: 181,
                            columnNumber: 17
                        }, void 0),
                        buttonType: "custom",
                        horizontalAlign: "center",
                        onToggleOpen: onPopupToggle,
                        render: ({ close: closePopup })=>/*#__PURE__*/ _jsxDEV(PopupList.ButtonGroup, {
                                children: relatedCollections.map((relatedCollection)=>{
                                    if (permissions.collections[relatedCollection?.slug]?.create) {
                                        return /*#__PURE__*/ _jsxDEV(PopupList.Button, {
                                            className: `${baseClass}__relation-button--${relatedCollection?.slug}`,
                                            onClick: ()=>{
                                                closePopup();
                                                setSelectedCollection(relatedCollection?.slug);
                                            },
                                            children: getTranslation(relatedCollection?.labels?.singular, i18n)
                                        }, relatedCollection?.slug, false, {
                                            fileName: "src/elements/AddNewRelation/index.tsx",
                                            lineNumber: 198,
                                            columnNumber: 23
                                        }, void 0);
                                    }
                                    return null;
                                })
                            }, void 0, false, {
                                fileName: "src/elements/AddNewRelation/index.tsx",
                                lineNumber: 194,
                                columnNumber: 15
                            }, void 0),
                        size: "medium"
                    }, void 0, false, {
                        fileName: "src/elements/AddNewRelation/index.tsx",
                        lineNumber: 176,
                        columnNumber: 11
                    }, this),
                    collectionConfig && permissions.collections[collectionConfig?.slug]?.create && /*#__PURE__*/ _jsxDEV(DocumentDrawer, {
                        onSave: onSave
                    }, void 0, false, {
                        fileName: "src/elements/AddNewRelation/index.tsx",
                        lineNumber: 218,
                        columnNumber: 13
                    }, this)
                ]
            }, void 0, true, {
                fileName: "src/elements/AddNewRelation/index.tsx",
                lineNumber: 175,
                columnNumber: 9
            }, this)
        ]
    }, void 0, true, {
        fileName: "src/elements/AddNewRelation/index.tsx",
        lineNumber: 144,
        columnNumber: 5
    }, this);
};

//# sourceMappingURL=index.js.map