import React, { Fragment, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { components as SelectComponents } from 'react-select';
import { useDocumentDrawer } from '../../../../../elements/DocumentDrawer';
import Tooltip from '../../../../../elements/Tooltip';
import Edit from '../../../../../icons/Edit';
import { useAuth } from '../../../../../utilities/Auth';
import './index.scss';
const baseClass = 'relationship--single-value';
export const SingleValue = (props) => {
    var _a, _b, _c;
    const { data: { value, relationTo, label, }, children, selectProps: { selectProps: { setDrawerIsOpen, }, }, } = props;
    const [showTooltip, setShowTooltip] = useState(false);
    const { t } = useTranslation('general');
    const { permissions } = useAuth();
    const hasReadPermission = Boolean((_c = (_b = (_a = permissions === null || permissions === void 0 ? void 0 : permissions.collections) === null || _a === void 0 ? void 0 : _a[relationTo]) === null || _b === void 0 ? void 0 : _b.read) === null || _c === void 0 ? void 0 : _c.permission);
    const [DocumentDrawer, DocumentDrawerToggler, { isDrawerOpen }] = useDocumentDrawer({
        id: value.toString(),
        collectionSlug: relationTo,
    });
    useEffect(() => {
        if (typeof setDrawerIsOpen === 'function')
            setDrawerIsOpen(isDrawerOpen);
    }, [isDrawerOpen, setDrawerIsOpen]);
    return (React.createElement("div", { className: baseClass },
        React.createElement("div", { className: `${baseClass}__label` },
            React.createElement(SelectComponents.SingleValue, { ...props },
                React.createElement("div", { className: `${baseClass}__text` }, children),
                relationTo && hasReadPermission && (React.createElement(Fragment, null,
                    React.createElement(DocumentDrawerToggler, { className: `${baseClass}__drawer-toggler`, "aria-label": t('editLabel', { label }), onMouseDown: (e) => e.stopPropagation(), onMouseEnter: () => setShowTooltip(true), onMouseLeave: () => setShowTooltip(false), onClick: () => setShowTooltip(false) },
                        React.createElement(Tooltip, { className: `${baseClass}__tooltip`, show: showTooltip }, t('edit')),
                        React.createElement(Edit, null)))))),
        relationTo && hasReadPermission && (React.createElement(DocumentDrawer, null))));
};
