import { _objectSpread2 } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../../../hooks/useEngineContext.js";
import { getDefaultAuthMethods } from "../../AuthMethods/constants.js";
import AuthMethods from "../../AuthMethods/index.js";
import locales_default from "./locales.js";
import React, { useEffect, useState } from "react";
import { Alert, Button, Radio, Spin, Typography } from "antd";
import { locales } from "@pisell/utils";
import classNames from "classnames";
import { InfoCircleOutlined, UserOutlined } from "@ant-design/icons";
import "./AuthenticationMethods.less";
//#region src/components/authentication/admin/ChannelAuthSetting/AuthenticationMethods/index.tsx
const { Title, Paragraph, Text } = Typography;
const convertApiDataToComponent = (apiData) => {
	const { method } = apiData;
	const processedKeys = /* @__PURE__ */ new Set();
	const authMethods = Object.keys(method).map((key) => {
		processedKeys.add(key);
		const methodData = method[key];
		const methodId = key === "phone" ? "phone" : key;
		const baseMethod = getDefaultAuthMethods().find((m) => m.id === methodId);
		if (!baseMethod) return null;
		return _objectSpread2(_objectSpread2({}, baseMethod), {}, {
			enabled: methodData.enabled,
			sort: methodData.sort
		});
	}).filter(Boolean);
	getDefaultAuthMethods().forEach((defaultMethod) => {
		if (!processedKeys.has(defaultMethod.id)) authMethods.push(_objectSpread2(_objectSpread2({}, defaultMethod), {}, { enabled: false }));
	});
	authMethods.sort((a, b) => {
		var _a$sort, _b$sort;
		return ((_a$sort = a.sort) !== null && _a$sort !== void 0 ? _a$sort : 0) - ((_b$sort = b.sort) !== null && _b$sort !== void 0 ? _b$sort : 0);
	});
	return {
		authMethods,
		globalMethods: authMethods.map((method) => {
			return {
				method: method.id === "phone" ? "phoneNumber" : method.id,
				enabled: method.enabled,
				label: {
					email: {
						en: "Email",
						"zh-CN": "邮箱",
						"zh-HK": "郵箱",
						ja: "メール",
						pt: "E-mail"
					},
					phone: {
						en: "Phone Number",
						"zh-CN": "手机号",
						"zh-HK": "手機號",
						ja: "電話番号",
						pt: "Número de Telefone"
					},
					facebook: {
						en: "Facebook",
						"zh-CN": "Facebook",
						"zh-HK": "Facebook",
						ja: "Facebook",
						pt: "Facebook"
					},
					apple: {
						en: "Apple",
						"zh-CN": "Apple",
						"zh-HK": "Apple",
						ja: "Apple",
						pt: "Apple"
					},
					guest: {
						en: "Guest",
						"zh-CN": "访客",
						"zh-HK": "訪客",
						ja: "ゲスト",
						pt: "Convidado"
					}
				}[method.id] || {
					en: method.id,
					"zh-CN": method.id,
					"zh-HK": method.id
				}
			};
		})
	};
};
const mockGlobalMethods = [
	{
		method: "email",
		enabled: true,
		label: {
			en: "Email",
			"zh-CN": "邮箱",
			"zh-HK": "郵箱",
			ja: "メール",
			pt: "E-mail"
		}
	},
	{
		method: "phoneNumber",
		enabled: true,
		label: {
			en: "Phone Number",
			"zh-CN": "手机号",
			"zh-HK": "手機號",
			ja: "電話番号",
			pt: "Número de Telefone"
		}
	},
	{
		method: "facebook",
		enabled: true,
		label: {
			en: "Facebook",
			"zh-CN": "Facebook",
			"zh-HK": "Facebook",
			ja: "Facebook",
			pt: "Facebook"
		}
	},
	{
		method: "apple",
		enabled: true,
		label: {
			en: "Apple",
			"zh-CN": "Apple",
			"zh-HK": "Apple",
			ja: "Apple",
			pt: "Apple"
		}
	}
];
const AuthenticationMethods = ({ className, style, value, onChange, globalMethods = mockGlobalMethods, onConfigureGlobal }) => {
	var _context$engine;
	const context = useEngineContext();
	locales.init(locales_default, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || "en");
	const { request, data, history } = context.appHelper.utils.getApp();
	const dataKey = "auth.customer";
	const [tenantId, setTenantId] = useState(null);
	const [loading, setLoading] = useState(true);
	const [mode, setMode] = useState("default");
	const [authMethods, setAuthMethods] = useState(getDefaultAuthMethods());
	const [fetchedGlobalMethods, setFetchedGlobalMethods] = useState(mockGlobalMethods);
	useEffect(() => {
		const coreData = data.storage.getStorage("core");
		if (coreData) try {
			var _coreDataJson$tenant;
			const coreDataJson = JSON.parse(coreData);
			if (coreDataJson === null || coreDataJson === void 0 || (_coreDataJson$tenant = coreDataJson.tenant) === null || _coreDataJson$tenant === void 0 ? void 0 : _coreDataJson$tenant.id) setTenantId(coreDataJson.tenant.id);
		} catch (error) {
			console.error("Error parsing core data:", error);
		}
	}, [data.storage]);
	useEffect(() => {
		if (tenantId) {
			setLoading(true);
			request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`).then((res) => {
				var _res$data;
				console.log("res_customer_auth_methods", res);
				if (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.length) {
					var _res$data$;
					const { authMethods: convertedAuthMethods, globalMethods: convertedGlobalMethods } = convertApiDataToComponent((_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value);
					setFetchedGlobalMethods(convertedGlobalMethods);
					console.log("Converted data:", {
						authMethods: convertedAuthMethods,
						globalMethods: convertedGlobalMethods
					});
				}
				setLoading(false);
			}).catch((error) => {
				console.error("Error fetching tenant data:", error);
				setLoading(false);
			});
		}
	}, [tenantId, request]);
	useEffect(() => {
		if (value) {
			setMode(value.mode || "default");
			console.log("同步外部value - 输入的 value.methods:", value.methods);
			const updatedMethods = getDefaultAuthMethods().map((method, index) => {
				var _value$methods, _method$sort;
				const methodKey = method.id === "phone" ? "phoneNumber" : method.id;
				const config = (_value$methods = value.methods) === null || _value$methods === void 0 ? void 0 : _value$methods[methodKey];
				if (config && typeof config === "object" && "enabled" in config) {
					var _config$enabled, _config$sort;
					return _objectSpread2(_objectSpread2({}, method), {}, {
						enabled: (_config$enabled = config.enabled) !== null && _config$enabled !== void 0 ? _config$enabled : method.enabled,
						sort: (_config$sort = config.sort) !== null && _config$sort !== void 0 ? _config$sort : index
					});
				}
				return _objectSpread2(_objectSpread2({}, method), {}, { sort: (_method$sort = method.sort) !== null && _method$sort !== void 0 ? _method$sort : index });
			}).sort((a, b) => {
				var _a$sort2, _b$sort2;
				return ((_a$sort2 = a.sort) !== null && _a$sort2 !== void 0 ? _a$sort2 : 0) - ((_b$sort2 = b.sort) !== null && _b$sort2 !== void 0 ? _b$sort2 : 0);
			});
			console.log("同步外部value - 生成的 updatedMethods:", updatedMethods);
			setAuthMethods(updatedMethods);
		}
	}, [value]);
	const convertAuthMethodsToConfig = (methods) => {
		console.log("convertAuthMethodsToConfig - 输入的 methods:", methods);
		const config = {};
		methods.forEach((method, index) => {
			var _method$sort2;
			const key = method.id === "phone" ? "phoneNumber" : method.id;
			config[key] = {
				enabled: method.enabled,
				sort: (_method$sort2 = method.sort) !== null && _method$sort2 !== void 0 ? _method$sort2 : index
			};
		});
		console.log("convertAuthMethodsToConfig - 输出的 config:", config);
		return config;
	};
	const handleModeChange = (e) => {
		setMode(e.target.value);
		onChange === null || onChange === void 0 || onChange({
			mode: e.target.value,
			methods: convertAuthMethodsToConfig(authMethods)
		});
	};
	const handleConfigureGlobal = () => {
		history.push("/system-settings/auth/customer");
	};
	const handleOAuthConfig = () => {
		history.push("/system-settings/auth/oauth-config");
	};
	const handleAuthMethodsOrderChange = (methods) => {
		console.log("handleAuthMethodsOrderChange", methods);
		setAuthMethods(methods);
		onChange === null || onChange === void 0 || onChange({
			mode,
			methods: convertAuthMethodsToConfig(methods)
		});
	};
	const handleAuthMethodsToggle = (method, enabled) => {
		const updatedMethods = authMethods.map((m) => m.id === method.id ? _objectSpread2(_objectSpread2({}, m), {}, { enabled }) : m);
		setAuthMethods(updatedMethods);
		setTimeout(() => {
			onChange === null || onChange === void 0 || onChange({
				mode,
				methods: convertAuthMethodsToConfig(updatedMethods)
			});
		}, 0);
	};
	const renderMethodTag = (method) => {
		var _context$engine2;
		const statusText = method.enabled ? locales.getText("auth.methods.status.enabled") : locales.getText("auth.methods.status.disabled");
		const locale = (context === null || context === void 0 || (_context$engine2 = context.engine) === null || _context$engine2 === void 0 || (_context$engine2 = _context$engine2.props) === null || _context$engine2 === void 0 ? void 0 : _context$engine2.locale) || "en";
		const label = method.label[locale] || method.label.en;
		return /* @__PURE__ */ React.createElement("div", {
			key: method.method,
			className: "auth-method-item"
		}, /* @__PURE__ */ React.createElement("span", { className: `auth-method-status ${method.enabled ? "enabled" : "disabled"}` }, statusText), /* @__PURE__ */ React.createElement(Text, null, label));
	};
	if (loading) return /* @__PURE__ */ React.createElement("div", {
		className: classNames("authentication-methods", className),
		style: _objectSpread2(_objectSpread2({}, style), {}, {
			display: "flex",
			justifyContent: "center",
			alignItems: "center",
			minHeight: "400px"
		})
	}, /* @__PURE__ */ React.createElement(Spin, { size: "large" }));
	return /* @__PURE__ */ React.createElement("div", {
		className: classNames("authentication-methods", className),
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-upper" }, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 2,
		className: "authentication-methods-title"
	}, locales.getText("auth.methods.title"))), /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-mode" }, /* @__PURE__ */ React.createElement(Radio.Group, {
		value: mode,
		onChange: handleModeChange
	}, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-mode-wrapper" }, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-mode-option" }, /* @__PURE__ */ React.createElement(Radio, { value: "default" }, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-mode-content" }, /* @__PURE__ */ React.createElement(Text, {
		strong: true,
		className: "authentication-methods-mode-title"
	}, locales.getText("auth.methods.mode.default.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "authentication-methods-mode-description" }, locales.getText("auth.methods.mode.default.description")), /* @__PURE__ */ React.createElement(Button, {
		type: "link",
		className: "authentication-methods-configure-link",
		onClick: handleConfigureGlobal,
		style: {
			padding: 0,
			height: "auto"
		}
	}, locales.getText("auth.methods.mode.default.configure"))))), /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-mode-option" }, /* @__PURE__ */ React.createElement(Radio, { value: "custom" }, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-mode-content" }, /* @__PURE__ */ React.createElement(Text, {
		strong: true,
		className: "authentication-methods-mode-title"
	}, locales.getText("auth.methods.mode.custom.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "authentication-methods-mode-description" }, locales.getText("auth.methods.mode.custom.description"))))))))), /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-middle" }, mode === "default" && /* @__PURE__ */ React.createElement(Alert, {
		message: locales.getText("auth.methods.preview.title"),
		description: locales.getText("auth.methods.preview.description"),
		type: "info",
		showIcon: true,
		icon: /* @__PURE__ */ React.createElement(InfoCircleOutlined, null)
	}), mode === "custom" && /* @__PURE__ */ React.createElement(Alert, {
		message: locales.getText("auth.methods.custom.warning.title"),
		description: locales.getText("auth.methods.custom.warning.description"),
		type: "warning",
		showIcon: true
	})), /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-lower" }, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-customer" }, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-customer-left" }, /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-customer-header" }, /* @__PURE__ */ React.createElement(UserOutlined, { className: "authentication-methods-customer-icon" }), /* @__PURE__ */ React.createElement(Title, {
		level: 4,
		className: "authentication-methods-customer-title"
	}, locales.getText("auth.methods.customer.title"))), /* @__PURE__ */ React.createElement(Paragraph, { className: "authentication-methods-customer-description" }, locales.getText("auth.methods.customer.description"))), /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-customer-right" }, mode === "default" ? /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-inherited" }, /* @__PURE__ */ React.createElement(Paragraph, { className: "authentication-methods-inherited-title" }, locales.getText("auth.methods.preview.inherited")), /* @__PURE__ */ React.createElement("div", { className: "authentication-methods-list" }, fetchedGlobalMethods.map(renderMethodTag))) : /* @__PURE__ */ React.createElement(AuthMethods, {
		methods: authMethods,
		onOrderChange: handleAuthMethodsOrderChange,
		onToggle: handleAuthMethodsToggle,
		onConfigClick: handleOAuthConfig,
		enableSetting: false
	})))));
};
//#endregion
export { AuthenticationMethods as default };
