import { useClipboard } from "../../../hooks/useClipboard.js";
import { localizationKeys } from "../../../localization/localizationKeys.js";
import check_default from "../../../icons/check.js";
import copy_default from "../../../icons/copy.js";
import rotate_left_right_default from "../../../icons/rotate-left-right.js";
import { useLocalizations } from "../../../localization/makeLocalizable.js";
import { common } from "../../../styledSystem/common.js";
import { mqu } from "../../../styledSystem/breakpoints.js";
import { descriptors } from "../../../customizables/elementDescriptors.js";
import { useCardState } from "../../../elements/contexts/index.js";
import { Flow } from "../../../customizables/Flow.js";
import { Badge, Box, Button, Dd, Dl, Dt, Flex, Heading, Icon, Spinner, Table, Tbody, Td, Text, Th, Thead, Tr } from "../../../customizables/index.js";
import { IconButton } from "../../../elements/IconButton.js";
import { handleError } from "../../../utils/errorHandler.js";
import { Pagination } from "../../../elements/Pagination.js";
import { Drawer } from "../../../elements/Drawer.js";
import { useConfigureSSO } from "../ConfigureSSOContext.js";
import { useWizard } from "../elements/Wizard/WizardContext.js";
import { Step } from "../elements/Step.js";
import { ProfileSection } from "../../../elements/Section.js";
import { TestRunHowToFixSection } from "./TestRunHowToFixSection.js";
import { useState } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "@emotion/react/jsx-runtime";
import { __internal_useEnterpriseConnectionTestRuns, useUser } from "@clerk/shared/react/index";

//#region src/components/ConfigureSSO/steps/TestConfigurationStep.tsx
const TEST_RUNS_PAGE_SIZE = 5;
const TEST_RESULTS_TABLE_COLUMN_COUNT = 3;
const TestConfigurationStep = () => {
	const { goNext, goPrev } = useWizard();
	const { enterpriseConnection } = useConfigureSSO();
	const card = useCardState();
	const [currentPage, setCurrentPage] = useState(1);
	const { data: testRuns, totalCount, isLoading: areTestRunsLoading, isPolling, revalidate: revalidateTestRuns } = __internal_useEnterpriseConnectionTestRuns({
		enterpriseConnectionId: enterpriseConnection?.id ?? null,
		params: {
			initialPage: currentPage,
			pageSize: TEST_RUNS_PAGE_SIZE
		}
	});
	const pageCount = totalCount ? Math.ceil(totalCount / TEST_RUNS_PAGE_SIZE) : 0;
	const handleTestRunCreated = () => {
		setCurrentPage(1);
		revalidateTestRuns();
	};
	return /* @__PURE__ */ jsx(Flow.Part, {
		part: "testSso",
		children: /* @__PURE__ */ jsxs(Step, {
			elementDescriptor: descriptors.configureSSOStep,
			elementId: descriptors.configureSSOStep.setId("test"),
			children: [
				/* @__PURE__ */ jsx(Step.Header, {
					title: localizationKeys("configureSSO.testConfigurationStep.title"),
					description: localizationKeys("configureSSO.testConfigurationStep.subtitle")
				}),
				/* @__PURE__ */ jsxs(Step.Body, { children: [/* @__PURE__ */ jsx(Step.Section, {
					sx: (theme) => ({
						borderBottomWidth: theme.borderWidths.$normal,
						borderBottomStyle: theme.borderStyles.$solid,
						borderBottomColor: theme.colors.$borderAlpha100
					}),
					children: /* @__PURE__ */ jsxs(ProfileSection.Root, {
						title: localizationKeys("configureSSO.testConfigurationStep.testUrl.title"),
						id: "testSsoUrl",
						centered: false,
						sx: (t) => ({
							borderTopWidth: 0,
							paddingTop: 0,
							paddingBottom: 0,
							flexDirection: "column-reverse",
							gap: t.space.$1
						}),
						children: [/* @__PURE__ */ jsx(Text, {
							colorScheme: "secondary",
							localizationKey: localizationKeys("configureSSO.testConfigurationStep.testUrl.subtitle")
						}), /* @__PURE__ */ jsx(ProfileSection.Item, {
							id: "testSsoUrl",
							sx: { paddingInlineStart: 0 },
							children: /* @__PURE__ */ jsxs(Flex, {
								gap: 2,
								children: [/* @__PURE__ */ jsx(CopyTestUrlButton, { onTestRunCreated: handleTestRunCreated }), /* @__PURE__ */ jsxs(Button, {
									variant: "bordered",
									colorScheme: "secondary",
									size: "xs",
									onClick: () => void revalidateTestRuns(),
									isDisabled: areTestRunsLoading,
									sx: (t) => ({ gap: t.space.$1x5 }),
									children: [/* @__PURE__ */ jsx(Icon, {
										icon: rotate_left_right_default,
										size: "sm",
										colorScheme: "neutral"
									}), /* @__PURE__ */ jsx(Text, {
										as: "span",
										localizationKey: localizationKeys("configureSSO.testConfigurationStep.testResults.actionLabel__refresh")
									})]
								})]
							})
						})]
					})
				}), /* @__PURE__ */ jsx(Step.Section, {
					sx: {
						flex: 1,
						minHeight: 0
					},
					children: /* @__PURE__ */ jsx(ProfileSection.Root, {
						title: localizationKeys("configureSSO.testConfigurationStep.testResults.title"),
						id: "testResults",
						centered: false,
						sx: (t) => ({
							borderTopWidth: 0,
							paddingTop: 0,
							paddingBottom: 0,
							flexDirection: "column-reverse",
							gap: t.space.$2,
							flex: 1,
							minHeight: 0,
							"& > *:first-of-type": {
								flex: 1,
								minHeight: 0
							}
						}),
						children: /* @__PURE__ */ jsx(TestResultsTable, {
							rows: testRuns ?? [],
							isPolling,
							isLoading: areTestRunsLoading,
							page: currentPage,
							pageCount,
							pageSize: TEST_RUNS_PAGE_SIZE,
							totalCount: totalCount ?? 0,
							onPageChange: setCurrentPage,
							onTestRunCreated: handleTestRunCreated
						})
					})
				})] }),
				card.error ? /* @__PURE__ */ jsx(Box, {
					sx: (t) => ({
						flexShrink: 0,
						paddingInline: t.space.$5,
						paddingBlock: t.space.$3,
						borderTopWidth: t.borderWidths.$normal,
						borderTopStyle: t.borderStyles.$solid,
						borderTopColor: t.colors.$borderAlpha100
					}),
					children: /* @__PURE__ */ jsx(Text, {
						as: "p",
						variant: "body",
						sx: (t) => ({
							color: t.colors.$danger500,
							fontSize: t.fontSizes.$sm
						}),
						children: card.error
					})
				}) : null,
				/* @__PURE__ */ jsxs(Step.Footer, { children: [/* @__PURE__ */ jsx(Step.Footer.Previous, { onClick: () => goPrev() }), /* @__PURE__ */ jsx(ContinueTestSsoStepButton, {
					enterpriseConnectionId: enterpriseConnection?.id,
					isConnectionActive: enterpriseConnection?.active,
					onContinue: () => void goNext()
				})] })
			]
		})
	});
};
const ContinueTestSsoStepButton = ({ enterpriseConnectionId, isConnectionActive, onContinue }) => {
	const { user } = useUser();
	const { t } = useLocalizations();
	const card = useCardState();
	const [isValidating, setIsValidating] = useState(false);
	const handleContinue = async () => {
		if (!user || !enterpriseConnectionId) return;
		setIsValidating(true);
		card.setError(void 0);
		try {
			if ((await user.getEnterpriseConnectionTestRuns(enterpriseConnectionId, {
				initialPage: 1,
				pageSize: 1,
				status: ["success"]
			})).data.length > 0) onContinue();
			else card.setError(t(localizationKeys("configureSSO.testConfigurationStep.error__noSuccessfulTestRun")));
		} catch (err) {
			handleError(err, [], card.setError);
		} finally {
			setIsValidating(false);
		}
	};
	return /* @__PURE__ */ jsx(Step.Footer.Continue, {
		onClick: () => void handleContinue(),
		isLoading: isValidating,
		isDisabled: !enterpriseConnectionId || isConnectionActive
	});
};
const TestResultsTable = ({ rows, isLoading, isPolling, onTestRunCreated, page, pageCount, pageSize, totalCount, onPageChange }) => {
	const { t } = useLocalizations();
	const { contentRef } = useConfigureSSO();
	const [selectedTestRun, setSelectedTestRun] = useState(null);
	const drawerTitle = selectedTestRun?.status === "failed" ? selectedTestRun.logs?.[0]?.shortMessage || t(localizationKeys("configureSSO.testConfigurationStep.testRunDetails.title")) : t(localizationKeys("configureSSO.testConfigurationStep.testRunDetails.title"));
	return /* @__PURE__ */ jsxs(Fragment$1, { children: [
		/* @__PURE__ */ jsx(Flex, {
			direction: "col",
			sx: (t$1) => ({
				width: "100%",
				flex: "0 1 auto",
				minHeight: 0,
				overflowY: "auto",
				borderWidth: t$1.borderWidths.$normal,
				borderStyle: t$1.borderStyles.$solid,
				borderColor: t$1.colors.$borderAlpha150,
				borderRadius: t$1.radii.$lg,
				...common.unstyledScrollbar(t$1),
				[mqu.sm]: {
					overflowX: "auto",
					padding: t$1.space.$0x25
				}
			}),
			children: /* @__PURE__ */ jsxs(Table, {
				tableHeadVisuallyHidden: !rows.length,
				sx: (t$1) => ({
					background: t$1.colors.$colorBackground,
					"&&": {
						border: "none",
						borderRadius: 0
					}
				}),
				children: [/* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
					/* @__PURE__ */ jsx(Th, { localizationKey: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.timestamp") }),
					/* @__PURE__ */ jsx(Th, { localizationKey: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.sectionTitle") }),
					/* @__PURE__ */ jsx(Th, { localizationKey: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.status") })
				] }) }), /* @__PURE__ */ jsx(Tbody, { children: isLoading || isPolling ? /* @__PURE__ */ jsx(Tr, { children: /* @__PURE__ */ jsx(Td, {
					colSpan: TEST_RESULTS_TABLE_COLUMN_COUNT,
					children: /* @__PURE__ */ jsxs(Flex, {
						direction: "col",
						align: "center",
						gap: 2,
						sx: (t$1) => ({ padding: `${t$1.space.$10} 0` }),
						children: [/* @__PURE__ */ jsx(Spinner, {
							colorScheme: "primary",
							elementDescriptor: descriptors.spinner
						}), /* @__PURE__ */ jsx(Text, {
							colorScheme: "secondary",
							localizationKey: isPolling ? localizationKeys("configureSSO.testConfigurationStep.testResults.polling") : void 0
						})]
					})
				}) }) : !rows.length ? /* @__PURE__ */ jsx(Tr, { children: /* @__PURE__ */ jsx(Td, {
					colSpan: TEST_RESULTS_TABLE_COLUMN_COUNT,
					children: /* @__PURE__ */ jsx(Flex, {
						align: "center",
						justify: "center",
						sx: (t$1) => ({
							padding: `${t$1.space.$10} 0`,
							flex: 1
						}),
						children: /* @__PURE__ */ jsx(CopyTestUrlButton, { onTestRunCreated })
					})
				}) }) : rows.map((row) => /* @__PURE__ */ jsxs(Tr, {
					onClick: () => setSelectedTestRun(row),
					sx: (t$1) => ({
						cursor: "pointer",
						"&:hover > td": { backgroundColor: t$1.colors.$neutralAlpha50 }
					}),
					children: [
						/* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(TestRunTimestampCell, { testRun: row }) }),
						/* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(TestRunDetailsCell, { testRun: row }) }),
						/* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(TestRunStatusCell, { testRun: row }) })
					]
				}, row.id)) })]
			})
		}),
		pageCount > 1 ? /* @__PURE__ */ jsx(Box, {
			sx: { flexShrink: 0 },
			children: /* @__PURE__ */ jsx(Pagination, {
				page: Math.min(page, pageCount),
				count: pageCount,
				onChange: onPageChange,
				siblingCount: 1,
				rowInfo: {
					allRowsCount: totalCount,
					startingRow: totalCount > 0 ? Math.max(0, (page - 1) * pageSize) + 1 : 0,
					endingRow: Math.min(page * pageSize, totalCount)
				}
			})
		}) : null,
		/* @__PURE__ */ jsxs(Drawer.Root, {
			open: selectedTestRun !== null,
			onOpenChange: (open) => {
				if (!open) setSelectedTestRun(null);
			},
			strategy: "absolute",
			portalProps: { root: contentRef },
			children: [/* @__PURE__ */ jsx(Drawer.Overlay, {}), /* @__PURE__ */ jsxs(Drawer.Content, { children: [/* @__PURE__ */ jsx(Drawer.Header, { title: drawerTitle }), selectedTestRun ? /* @__PURE__ */ jsx(TestRunDetailsBody, { testRun: selectedTestRun }) : null] })]
		})
	] });
};
const useTestRunFormattedTimestamp = (testRun) => {
	const { locale } = useLocalizations();
	if (!testRun.createdAt) return null;
	return {
		time: new Intl.DateTimeFormat(locale, { timeStyle: "medium" }).format(testRun.createdAt),
		day: new Intl.DateTimeFormat(locale, {
			month: "short",
			day: "numeric"
		}).format(testRun.createdAt)
	};
};
const TestRunTimestampCell = ({ testRun }) => {
	const formatted = useTestRunFormattedTimestamp(testRun);
	if (!formatted) return null;
	return /* @__PURE__ */ jsxs(Flex, {
		gap: 2,
		align: "baseline",
		sx: { whiteSpace: "nowrap" },
		children: [/* @__PURE__ */ jsx(Text, { children: formatted.time }), /* @__PURE__ */ jsx(Text, {
			colorScheme: "secondary",
			children: formatted.day
		})]
	});
};
const DetailRow = ({ title, children }) => /* @__PURE__ */ jsxs(Box, {
	as: "div",
	sx: (t) => ({
		display: "grid",
		gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
		gap: t.space.$2
	}),
	children: [/* @__PURE__ */ jsx(Dt, {
		localizationKey: title,
		sx: (t) => ({
			color: t.colors.$colorForeground,
			...common.textVariants(t).subtitle
		})
	}), /* @__PURE__ */ jsx(Dd, {
		sx: (t) => ({
			display: "grid",
			justifyContent: "end",
			color: t.colors.$colorForeground
		}),
		children
	})]
});
const TestRunDetailsBody = ({ testRun }) => {
	const formatted = useTestRunFormattedTimestamp(testRun);
	const failedLog = testRun.status === "failed" ? testRun.logs?.[0] : null;
	return /* @__PURE__ */ jsxs(Drawer.Body, {
		sx: (t) => ({
			display: "flex",
			flexDirection: "column",
			flex: 1,
			overflowY: "auto",
			padding: t.space.$4,
			gap: t.space.$4
		}),
		children: [
			/* @__PURE__ */ jsx(Heading, {
				as: "h3",
				textVariant: "h3",
				localizationKey: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.sectionTitle")
			}),
			/* @__PURE__ */ jsxs(Dl, {
				sx: (t) => ({
					display: "grid",
					gridRowGap: t.space.$2
				}),
				children: [formatted ? /* @__PURE__ */ jsx(DetailRow, {
					title: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.timestamp"),
					children: /* @__PURE__ */ jsxs(Flex, {
						gap: 2,
						align: "baseline",
						sx: { whiteSpace: "nowrap" },
						children: [/* @__PURE__ */ jsx(Text, { children: formatted.time }), /* @__PURE__ */ jsx(Text, {
							colorScheme: "secondary",
							children: formatted.day
						})]
					})
				}) : null, testRun.status === "failed" ? failedLog?.code ? /* @__PURE__ */ jsx(DetailRow, {
					title: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.errorCode"),
					children: /* @__PURE__ */ jsx(Text, {
						sx: (t) => ({ fontFamily: t.fonts.$mono }),
						children: failedLog.code
					})
				}) : null : /* @__PURE__ */ jsx(DetailRow, {
					title: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.status"),
					children: /* @__PURE__ */ jsx(TestRunStatusCell, { testRun })
				})]
			}),
			testRun.status === "failed" && failedLog?.message ? /* @__PURE__ */ jsx(FullMessageBlock, { message: failedLog.message }) : null,
			testRun.status === "failed" ? /* @__PURE__ */ jsx(TestRunHowToFixSection, { errorCode: failedLog?.code }) : null,
			testRun.status === "success" ? /* @__PURE__ */ jsx(ParsedUserInfoSection, { parsedUserInfo: testRun.parsedUserInfo }) : null
		]
	});
};
const ParsedUserInfoSection = ({ parsedUserInfo }) => {
	if (!parsedUserInfo?.emailAddress && !parsedUserInfo?.firstName) return null;
	return /* @__PURE__ */ jsxs(Flex, {
		direction: "col",
		gap: 3,
		sx: (t) => ({
			borderTopWidth: t.borderWidths.$normal,
			borderTopStyle: t.borderStyles.$solid,
			borderTopColor: t.colors.$borderAlpha100,
			paddingTop: t.space.$4
		}),
		children: [/* @__PURE__ */ jsx(Heading, {
			as: "h3",
			textVariant: "h3",
			localizationKey: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.parsedUserInfo.sectionTitle")
		}), /* @__PURE__ */ jsxs(Dl, {
			sx: (t) => ({
				display: "grid",
				gridRowGap: t.space.$2
			}),
			children: [parsedUserInfo.emailAddress ? /* @__PURE__ */ jsx(DetailRow, {
				title: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.parsedUserInfo.email"),
				children: /* @__PURE__ */ jsx(Text, {
					sx: (t) => ({ fontFamily: t.fonts.$mono }),
					children: parsedUserInfo.emailAddress
				})
			}) : null, parsedUserInfo.firstName ? /* @__PURE__ */ jsx(DetailRow, {
				title: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.parsedUserInfo.firstName"),
				children: /* @__PURE__ */ jsx(Text, {
					sx: (t) => ({ fontFamily: t.fonts.$mono }),
					children: parsedUserInfo.firstName
				})
			}) : null]
		})]
	});
};
const FullMessageBlock = ({ message }) => {
	const { t } = useLocalizations();
	const { onCopy, hasCopied } = useClipboard(message);
	const copyLabel = t(localizationKeys(hasCopied ? "configureSSO.testConfigurationStep.testRunDetails.runDetails.actionLabel__copied" : "configureSSO.testConfigurationStep.testRunDetails.runDetails.actionLabel__copy"));
	return /* @__PURE__ */ jsxs(Flex, {
		direction: "col",
		gap: 2,
		children: [/* @__PURE__ */ jsxs(Flex, {
			justify: "between",
			align: "center",
			gap: 4,
			children: [/* @__PURE__ */ jsx(Text, {
				colorScheme: "secondary",
				localizationKey: localizationKeys("configureSSO.testConfigurationStep.testRunDetails.runDetails.fullMessage")
			}), /* @__PURE__ */ jsx(IconButton, {
				variant: "ghost",
				colorScheme: "neutral",
				size: "xs",
				icon: hasCopied ? check_default : copy_default,
				"aria-label": copyLabel,
				onClick: () => onCopy()
			})]
		}), /* @__PURE__ */ jsx(Box, {
			as: "pre",
			sx: (t$1) => ({
				margin: 0,
				padding: t$1.space.$3,
				backgroundColor: t$1.colors.$colorBackground,
				borderWidth: t$1.borderWidths.$normal,
				borderStyle: t$1.borderStyles.$solid,
				borderColor: t$1.colors.$borderAlpha150,
				borderRadius: t$1.radii.$md,
				boxShadow: t$1.shadows.$cardContentShadow,
				fontFamily: t$1.fonts.$mono,
				fontSize: t$1.fontSizes.$sm,
				color: t$1.colors.$colorForeground,
				whiteSpace: "pre-wrap",
				wordBreak: "break-word"
			}),
			children: message
		})]
	});
};
const TestRunDetailsCell = ({ testRun }) => {
	if (testRun.status === "pending") return /* @__PURE__ */ jsx(Flex, {
		sx: (t) => ({ fontFamily: t.fonts.$mono }),
		children: /* @__PURE__ */ jsx(Text, { children: "-" })
	});
	if (testRun.status === "success") return /* @__PURE__ */ jsx(Flex, {
		sx: (t) => ({ fontFamily: t.fonts.$mono }),
		children: /* @__PURE__ */ jsx(Text, { children: testRun.parsedUserInfo?.emailAddress })
	});
	return /* @__PURE__ */ jsx(Flex, {
		sx: (t) => ({ fontFamily: t.fonts.$mono }),
		children: /* @__PURE__ */ jsx(Text, { children: testRun.logs?.[0]?.shortMessage })
	});
};
const TestRunStatusCell = ({ testRun }) => {
	if (testRun.status === "success") return /* @__PURE__ */ jsx(Badge, {
		colorScheme: "success",
		localizationKey: localizationKeys("configureSSO.testConfigurationStep.testResults.status__success")
	});
	if (testRun.status === "failed") return /* @__PURE__ */ jsx(Badge, {
		colorScheme: "danger",
		localizationKey: localizationKeys("configureSSO.testConfigurationStep.testResults.status__failed")
	});
	return /* @__PURE__ */ jsx(Badge, {
		colorScheme: "warning",
		localizationKey: localizationKeys("configureSSO.testConfigurationStep.testResults.status__pending")
	});
};
const CopyTestUrlButton = ({ onTestRunCreated }) => {
	const { t } = useLocalizations();
	const { user } = useUser();
	const card = useCardState();
	const { enterpriseConnection } = useConfigureSSO();
	const [testUrl, setTestUrl] = useState("");
	const [isCreatingTestRun, setIsCreatingTestRun] = useState(false);
	const { onCopy, hasCopied } = useClipboard(testUrl);
	const createTestRun = () => {
		if (!user || !enterpriseConnection) return;
		setIsCreatingTestRun(true);
		user.createEnterpriseConnectionTestRun(enterpriseConnection.id).then(({ url }) => {
			setTestUrl(url);
			onCopy(url);
			onTestRunCreated?.(url);
		}).catch((err) => handleError(err, [], card.setError)).finally(() => setIsCreatingTestRun(false));
	};
	return /* @__PURE__ */ jsxs(Button, {
		id: "testSsoUrl",
		variant: "bordered",
		colorScheme: "secondary",
		size: "xs",
		onClick: createTestRun,
		isDisabled: isCreatingTestRun,
		isLoading: isCreatingTestRun,
		loadingText: t(localizationKeys("configureSSO.testConfigurationStep.testUrl.actionLabel__copy")),
		sx: (t$1) => ({ gap: t$1.space.$1x5 }),
		children: [/* @__PURE__ */ jsx(Icon, {
			icon: hasCopied ? check_default : copy_default,
			size: "sm",
			colorScheme: "neutral"
		}), /* @__PURE__ */ jsx(Text, {
			as: "span",
			localizationKey: localizationKeys("configureSSO.testConfigurationStep.testUrl.actionLabel__copy")
		})]
	});
};

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