const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_types = require("../AuthMethods/types.js");
const require_SettingList = require("../AuthMethods/SettingList.js");
const require_locales = require("./locales.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _ant_design_icons = require("@ant-design/icons");
require("./OAuthConfig.less");
//#region src/components/authentication/admin/OAuthConfig/index.tsx
const { Title, Paragraph } = antd.Typography;
const OAuthConfig = ({ className, style, onSave }) => {
	var _context$engine;
	const context = require_useEngineContext.default();
	const app = context.appHelper.utils.getApp();
	const { request, data } = context.appHelper.utils.getApp();
	_pisell_utils.locales.init(require_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 [form] = antd.Form.useForm();
	const [drawerOpen, setDrawerOpen] = (0, react.useState)(false);
	const [currentProvider, setCurrentProvider] = (0, react.useState)(null);
	const [tenantId, setTenantId] = (0, react.useState)(null);
	(0, react.useEffect)(() => {
		console.log("app_init_oauth_config", app, context, data.storage);
	}, []);
	(0, react.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]);
	const providers = (0, react.useMemo)(() => {
		return [{
			id: "apple",
			name: _pisell_utils.locales.getText("oauth.provider.apple"),
			description: _pisell_utils.locales.getText("oauth.provider.apple.description"),
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.AppleOutlined, { style: {
				fontSize: 24,
				color: "#000000"
			} }),
			configured: false
		}, {
			id: "facebook",
			name: _pisell_utils.locales.getText("oauth.provider.facebook"),
			description: _pisell_utils.locales.getText("oauth.provider.facebook.description"),
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.FacebookOutlined, { style: {
				fontSize: 24,
				color: "#1877F2"
			} }),
			configured: false
		}];
	}, []);
	const authMethods = (0, react.useMemo)(() => {
		return providers.map((provider) => ({
			id: provider.id,
			type: provider.id.toUpperCase(),
			title: provider.name,
			category: require_types.AuthMethodCategory.OAUTH,
			description: provider.description,
			icon: provider.icon,
			enabled: provider.configured,
			hasSettings: true
		}));
	}, [providers]);
	const fetchProviderData = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (providerId) {
			if (!tenantId) return;
			const dataKey = `auth.oauth.${providerId}`;
			try {
				var _res$data;
				const res = yield request.get(`/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`);
				console.log(`res_oauth_${providerId}_data`, 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 configData = (_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value;
					console.log(`${providerId} config data:`, configData);
					if (providerId === "facebook") form.setFieldsValue({
						appid: configData.appid || "",
						secret_key: configData.secret_key || ""
					});
					else if (providerId === "apple") form.setFieldsValue({ identifier: configData.identifier || "" });
				}
			} catch (error) {
				console.error(`Error fetching ${providerId} data:`, error);
			}
		});
		return function fetchProviderData(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const handleSettings = (method) => {
		const provider = providers.find((p) => p.id === method.id);
		if (provider) {
			setCurrentProvider(provider);
			setDrawerOpen(true);
			fetchProviderData(provider.id);
		}
	};
	const handleDrawerClose = () => {
		setDrawerOpen(false);
		setCurrentProvider(null);
		form.resetFields();
	};
	const handleSaveSettings = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* () {
			if (!currentProvider || !tenantId) return;
			try {
				const values = yield form.validateFields();
				console.log("Saving settings:", values);
				const dataKey = `auth.oauth.${currentProvider.id}`;
				let configData = {};
				if (currentProvider.id === "facebook") configData = {
					appid: values.appid,
					secret_key: values.secret_key
				};
				else if (currentProvider.id === "apple") configData = { identifier: values.identifier };
				console.log("Saving to API:", {
					dataKey,
					configData
				});
				yield request.post(`/tenant/core/meta/tenant/${tenantId}`, { [dataKey]: configData });
				antd.message.success(_pisell_utils.locales.getText("oauth.save.success") || "保存成功");
				handleDrawerClose();
			} catch (error) {
				console.error("Validation failed or save error:", error);
				antd.message.error(_pisell_utils.locales.getText("oauth.save.error") || "保存失败");
			}
		});
		return function handleSaveSettings() {
			return _ref2.apply(this, arguments);
		};
	}();
	return /* @__PURE__ */ react.default.createElement("div", {
		className: `oauth-config ${className || ""}`,
		style
	}, /* @__PURE__ */ react.default.createElement("div", { className: "oauth-config-header" }, /* @__PURE__ */ react.default.createElement(Title, {
		level: 1,
		className: "oauth-config-title"
	}, _pisell_utils.locales.getText("oauth.config.title")), /* @__PURE__ */ react.default.createElement(Paragraph, { className: "oauth-config-description" }, _pisell_utils.locales.getText("oauth.config.description"))), /* @__PURE__ */ react.default.createElement("div", { className: "oauth-config-section" }, /* @__PURE__ */ react.default.createElement("div", { className: "oauth-config-section-layout" }, /* @__PURE__ */ react.default.createElement("div", { className: "oauth-config-section-header" }, /* @__PURE__ */ react.default.createElement(Title, {
		level: 2,
		className: "oauth-config-section-title"
	}, _pisell_utils.locales.getText("oauth.providers.title")), /* @__PURE__ */ react.default.createElement(Paragraph, { className: "oauth-config-section-description" }, _pisell_utils.locales.getText("oauth.providers.description"))), /* @__PURE__ */ react.default.createElement("div", { className: "oauth-config-section-content" }, /* @__PURE__ */ react.default.createElement(require_SettingList.default, {
		methods: authMethods,
		onSettings: handleSettings,
		enableSetting: true
	})))), /* @__PURE__ */ react.default.createElement(antd.Drawer, {
		title: currentProvider ? `${currentProvider.name} ${_pisell_utils.locales.getText("oauth.drawer.title")}` : "",
		placement: "right",
		width: 500,
		open: drawerOpen,
		onClose: handleDrawerClose
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		display: "flex",
		flexDirection: "column",
		height: "100%"
	} }, /* @__PURE__ */ react.default.createElement("div", { style: { flex: 1 } }, (currentProvider === null || currentProvider === void 0 ? void 0 : currentProvider.id) === "apple" && /* @__PURE__ */ react.default.createElement(antd.Form, {
		form,
		layout: "vertical"
	}, /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		label: _pisell_utils.locales.getText("oauth.apple.identifier"),
		name: "identifier",
		rules: [{
			required: true,
			message: _pisell_utils.locales.getText("oauth.apple.identifier.required")
		}]
	}, /* @__PURE__ */ react.default.createElement(antd.Input, { placeholder: _pisell_utils.locales.getText("oauth.apple.identifier.placeholder") }))), (currentProvider === null || currentProvider === void 0 ? void 0 : currentProvider.id) === "facebook" && /* @__PURE__ */ react.default.createElement(antd.Form, {
		form,
		layout: "vertical"
	}, /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		label: _pisell_utils.locales.getText("oauth.facebook.appId"),
		name: "appid",
		rules: [{
			required: true,
			message: _pisell_utils.locales.getText("oauth.facebook.appId.required")
		}]
	}, /* @__PURE__ */ react.default.createElement(antd.Input, { placeholder: _pisell_utils.locales.getText("oauth.facebook.appId.placeholder") })), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		label: _pisell_utils.locales.getText("oauth.facebook.appSecret"),
		name: "secret_key",
		rules: [{
			required: true,
			message: _pisell_utils.locales.getText("oauth.facebook.appSecret.required")
		}]
	}, /* @__PURE__ */ react.default.createElement(antd.Input.Password, { placeholder: _pisell_utils.locales.getText("oauth.facebook.appSecret.placeholder") })))), /* @__PURE__ */ react.default.createElement("div", { style: {
		display: "flex",
		gap: "8px",
		justifyContent: "flex-end",
		padding: "16px 0",
		borderTop: "1px solid #f0f0f0",
		marginTop: "auto"
	} }, /* @__PURE__ */ react.default.createElement(antd.Button, { onClick: handleDrawerClose }, _pisell_utils.locales.getText("oauth.button.cancel")), /* @__PURE__ */ react.default.createElement(antd.Button, {
		type: "primary",
		onClick: handleSaveSettings
	}, _pisell_utils.locales.getText("oauth.button.save"))))));
};
//#endregion
exports.default = OAuthConfig;
