import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2019-2026 GoodData Corporation
import { useCallback, useMemo, useState } from "react";
import { sortBy } from "lodash-es";
import { convertUserToAutomationRecipient } from "../../../../shared/utils/automationUtils.js";
import { createUser, matchUser } from "../../../utils/users.js";
import { isEmail } from "../../../utils/validate.js";
import { RecipientsSelectRenderer } from "./RecipientsSelectRenderer.js";
export function RecipientsSelect({ id, users, usersError, value, originalValue, onChange, loggedUser, allowEmptySelection, allowExternalRecipients, allowOnlyLoggedUserRecipients, maxRecipients, className, notificationChannels, notificationChannelId, showLabel = true, onKeyDownSubmit, externalRecipientOverride, }) {
    const [search, setSearch] = useState();
    const notificationChannel = useMemo(() => {
        return notificationChannels?.find((channel) => channel.id === notificationChannelId);
    }, [notificationChannelId, notificationChannels]);
    const options = useMemo(() => {
        if (externalRecipientOverride) {
            return search && isEmail(search) && allowExternalRecipients ? [createUser(search)] : [];
        }
        const validUsers = [
            ...(allowOnlyLoggedUserRecipients ? [] : users),
            ...(allowOnlyLoggedUserRecipients && loggedUser ? [loggedUser] : []),
        ];
        const filteredUsers = search ? validUsers.filter((user) => matchUser(user, search)) : validUsers;
        const mappedUsers = sortBy(filteredUsers?.map(convertUserToAutomationRecipient) ?? [], "user.email");
        // If there is no user found and the search is an email, add it as an external recipient
        if (search && mappedUsers.length === 0 && isEmail(search) && allowExternalRecipients) {
            mappedUsers.push(createUser(search));
        }
        return mappedUsers;
    }, [
        allowOnlyLoggedUserRecipients,
        loggedUser,
        search,
        users,
        allowExternalRecipients,
        externalRecipientOverride,
    ]);
    const onLoadHandler = useCallback((queryOptions) => {
        setSearch(queryOptions?.search);
    }, [setSearch]);
    const loggedUserPrepared = useMemo(() => {
        return loggedUser ? convertUserToAutomationRecipient(loggedUser) : undefined;
    }, [loggedUser]);
    return (_jsx(RecipientsSelectRenderer, { id: id, canListUsersInProject: true, isMulti: true, options: options, value: value, originalValue: originalValue, onChange: onChange, onLoad: onLoadHandler, loggedUser: loggedUserPrepared, allowOnlyLoggedUserRecipients: allowOnlyLoggedUserRecipients, allowEmptySelection: allowEmptySelection, allowExternalRecipients: allowExternalRecipients, maxRecipients: maxRecipients, className: className, notificationChannel: notificationChannel, usersError: usersError, showLabel: showLabel, onKeyDownSubmit: onKeyDownSubmit, externalRecipientOverride: externalRecipientOverride }));
}
