import { useEnvironment } from "../../contexts/EnvironmentContext.js";
import { localizationKeys } from "../../localization/localizationKeys.js";
import { createListFormat } from "../../utils/passwordUtils.js";
import { useLocalizations } from "../../localization/makeLocalizable.js";
import { mqu } from "../../styledSystem/breakpoints.js";
import { useFormControl } from "../../utils/useFormControl.js";
import { useCardState } from "../../elements/contexts/index.js";
import { Flex } from "../../customizables/index.js";
import { handleError } from "../../utils/errorHandler.js";
import { Form } from "../../elements/Form.js";
import { FormButtonContainer } from "../../elements/FormButtons.js";
import { TagInput } from "../../elements/TagInput.js";
import { useFetchRoles } from "../../hooks/useFetchRoles.js";
import { RoleSelect } from "./MemberListTable.js";
import { useEffect, useState } from "react";
import { useOrganization } from "@clerk/shared/react";
import { jsx, jsxs } from "@emotion/react/jsx-runtime";
import { isClerkAPIResponseError } from "@clerk/shared/error";

//#region src/components/OrganizationProfile/InviteMembersForm.tsx
const isEmail = (str) => /^\S+@\S+\.\S+$/.test(str);
const InviteMembersForm = (props) => {
	const { onSuccess, onReset, resetButtonLabel } = props;
	const { organization, invitations } = useOrganization({ invitations: {
		pageSize: 10,
		keepPreviousData: true
	} });
	const card = useCardState();
	const { t, locale } = useLocalizations();
	const [isValidUnsubmittedEmail, setIsValidUnsubmittedEmail] = useState(false);
	const validateUnsubmittedEmail = (value) => setIsValidUnsubmittedEmail(isEmail(value));
	const emailAddressField = useFormControl("emailAddress", "", {
		type: "text",
		label: localizationKeys("formFieldLabel__emailAddresses")
	});
	const roleField = useFormControl("role", "", { label: localizationKeys("formFieldLabel__role") });
	if (!organization) return null;
	const { props: { setError, setWarning, setSuccess, setInfo, isFocused, validatePassword, setHasPassedComplexity, hasPassedComplexity, feedback, feedbackType, clearFeedback,...restEmailAddressProps } } = emailAddressField;
	const canSubmit = (!!emailAddressField.value.length || isValidUnsubmittedEmail) && !!roleField.value;
	const onSubmit = (e) => {
		e.preventDefault();
		if (!canSubmit) return;
		const submittedData = new FormData(e.currentTarget);
		return organization.inviteMembers({
			emailAddresses: emailAddressField.value.split(","),
			role: submittedData.get("role")
		}).then(async () => {
			await invitations?.revalidate?.();
			return onSuccess?.();
		}).catch((err) => {
			if (!isClerkAPIResponseError(err)) {
				handleError(err, [], card.setError);
				return;
			}
			removeInvalidEmails(err.errors[0]);
			switch (err.errors?.[0]?.code) {
				case "duplicate_record": {
					const unlocalizedEmailsList = err.errors[0].meta?.emailAddresses || [];
					card.setError(t(localizationKeys("organizationProfile.invitePage.detailsTitle__inviteFailed", { email_addresses: createListFormat(unlocalizedEmailsList, locale) })));
					break;
				}
				case "already_a_member_in_organization": {
					const email = (err.errors[0].longMessage ?? "").match(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/)?.[0];
					handleError(err, [], (err$1) => email ? card.setError(t(localizationKeys("unstable__errors.already_a_member_in_organization", { email }))) : card.setError(err$1));
					break;
				}
				default: handleError(err, [], card.setError);
			}
		});
	};
	const removeInvalidEmails = (err) => {
		const invalidEmails = new Set([...err.meta?.emailAddresses ?? [], ...err.meta?.identifiers ?? []]);
		const emails = emailAddressField.value.split(",");
		emailAddressField.setValue(emails.filter((e) => !invalidEmails.has(e)).join(","));
	};
	return /* @__PURE__ */ jsxs(Form.Root, {
		onSubmit,
		children: [/* @__PURE__ */ jsx(Form.ControlRow, {
			elementId: emailAddressField.id,
			children: /* @__PURE__ */ jsx(TagInput, {
				...restEmailAddressProps,
				autoFocus: true,
				validate: isEmail,
				sx: { width: "100%" },
				validateUnsubmittedEmail,
				placeholder: localizationKeys("formFieldInputPlaceholder__emailAddresses")
			})
		}), /* @__PURE__ */ jsxs(Flex, {
			align: "center",
			justify: "between",
			sx: (t$1) => ({
				marginTop: t$1.space.$2,
				gap: t$1.space.$4,
				flexWrap: "wrap",
				[mqu.sm]: { justifyContent: "center" }
			}),
			children: [/* @__PURE__ */ jsx(AsyncRoleSelect, { ...roleField }), /* @__PURE__ */ jsxs(FormButtonContainer, {
				sx: (t$1) => ({
					margin: t$1.space.$none,
					flexWrap: "wrap",
					justifyContent: "center"
				}),
				children: [/* @__PURE__ */ jsx(Form.SubmitButton, {
					block: false,
					isDisabled: !canSubmit,
					localizationKey: localizationKeys("organizationProfile.invitePage.formButtonPrimary__continue")
				}), /* @__PURE__ */ jsx(Form.ResetButton, {
					localizationKey: resetButtonLabel || localizationKeys("userProfile.formButtonReset"),
					block: false,
					onClick: onReset
				})]
			})]
		})]
	});
};
const AsyncRoleSelect = (field) => {
	const { options, isLoading, hasRoleSetMigration } = useFetchRoles();
	const { t } = useLocalizations();
	const defaultRole = useDefaultRole();
	useEffect(() => {
		if (field.value || !defaultRole) return;
		if (!options?.some((option) => option.value === defaultRole)) return;
		field.setValue(defaultRole);
	}, [
		defaultRole,
		options,
		field
	]);
	return /* @__PURE__ */ jsx(Form.ControlRow, {
		elementId: field.id,
		children: /* @__PURE__ */ jsx(Flex, {
			direction: "col",
			gap: 2,
			children: /* @__PURE__ */ jsx(RoleSelect, {
				...field.props,
				roles: options,
				isDisabled: isLoading || hasRoleSetMigration,
				onChange: (value) => field.setValue(value),
				triggerSx: (t$1) => ({
					minWidth: t$1.sizes.$40,
					justifyContent: "space-between",
					display: "flex"
				}),
				optionListSx: (t$1) => ({ minWidth: t$1.sizes.$48 }),
				prefixLocalizationKey: `${t(localizationKeys("formFieldLabel__role"))}:`
			})
		})
	});
};
/**
* Determines default Role from the Organization settings or fallback to
* the only available Role.
*/
const useDefaultRole = () => {
	const { options } = useFetchRoles();
	const { organizationSettings } = useEnvironment();
	let defaultRole = organizationSettings.domains.defaultRole;
	if (!defaultRole && options?.length === 1) defaultRole = options[0].value;
	return defaultRole;
};

//#endregion
export { InviteMembersForm };
//# sourceMappingURL=InviteMembersForm.js.map