import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { AuthMethodCategory } from "../AuthMethods/types.js";
import SettingList from "../AuthMethods/SettingList.js";
import locales_default from "./locales.js";
import React, { useEffect, useMemo, useState } from "react";
import { Button, Drawer, Form, Input, Typography, message } from "antd";
import { locales } from "@pisell/utils";
import { AppleOutlined, FacebookOutlined } from "@ant-design/icons";
import "./OAuthConfig.less";
//#region src/components/authentication/admin/OAuthConfig/index.tsx
const { Title, Paragraph } = Typography;
const OAuthConfig = ({ className, style, onSave }) => {
	var _context$engine;
	const context = useEngineContext();
	const app = context.appHelper.utils.getApp();
	const { request, data } = context.appHelper.utils.getApp();
	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 [form] = Form.useForm();
	const [drawerOpen, setDrawerOpen] = useState(false);
	const [currentProvider, setCurrentProvider] = useState(null);
	const [tenantId, setTenantId] = useState(null);
	useEffect(() => {
		console.log("app_init_oauth_config", app, context, data.storage);
	}, []);
	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 = useMemo(() => {
		return [{
			id: "apple",
			name: locales.getText("oauth.provider.apple"),
			description: locales.getText("oauth.provider.apple.description"),
			icon: /* @__PURE__ */ React.createElement(AppleOutlined, { style: {
				fontSize: 24,
				color: "#000000"
			} }),
			configured: false
		}, {
			id: "facebook",
			name: locales.getText("oauth.provider.facebook"),
			description: locales.getText("oauth.provider.facebook.description"),
			icon: /* @__PURE__ */ React.createElement(FacebookOutlined, { style: {
				fontSize: 24,
				color: "#1877F2"
			} }),
			configured: false
		}];
	}, []);
	const authMethods = useMemo(() => {
		return providers.map((provider) => ({
			id: provider.id,
			type: provider.id.toUpperCase(),
			title: provider.name,
			category: AuthMethodCategory.OAUTH,
			description: provider.description,
			icon: provider.icon,
			enabled: provider.configured,
			hasSettings: true
		}));
	}, [providers]);
	const fetchProviderData = function() {
		var _ref = _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 = _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 });
				message.success(locales.getText("oauth.save.success") || "保存成功");
				handleDrawerClose();
			} catch (error) {
				console.error("Validation failed or save error:", error);
				message.error(locales.getText("oauth.save.error") || "保存失败");
			}
		});
		return function handleSaveSettings() {
			return _ref2.apply(this, arguments);
		};
	}();
	return /* @__PURE__ */ React.createElement("div", {
		className: `oauth-config ${className || ""}`,
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "oauth-config-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 1,
		className: "oauth-config-title"
	}, locales.getText("oauth.config.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "oauth-config-description" }, locales.getText("oauth.config.description"))), /* @__PURE__ */ React.createElement("div", { className: "oauth-config-section" }, /* @__PURE__ */ React.createElement("div", { className: "oauth-config-section-layout" }, /* @__PURE__ */ React.createElement("div", { className: "oauth-config-section-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 2,
		className: "oauth-config-section-title"
	}, locales.getText("oauth.providers.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "oauth-config-section-description" }, locales.getText("oauth.providers.description"))), /* @__PURE__ */ React.createElement("div", { className: "oauth-config-section-content" }, /* @__PURE__ */ React.createElement(SettingList, {
		methods: authMethods,
		onSettings: handleSettings,
		enableSetting: true
	})))), /* @__PURE__ */ React.createElement(Drawer, {
		title: currentProvider ? `${currentProvider.name} ${locales.getText("oauth.drawer.title")}` : "",
		placement: "right",
		width: 500,
		open: drawerOpen,
		onClose: handleDrawerClose
	}, /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		flexDirection: "column",
		height: "100%"
	} }, /* @__PURE__ */ React.createElement("div", { style: { flex: 1 } }, (currentProvider === null || currentProvider === void 0 ? void 0 : currentProvider.id) === "apple" && /* @__PURE__ */ React.createElement(Form, {
		form,
		layout: "vertical"
	}, /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("oauth.apple.identifier"),
		name: "identifier",
		rules: [{
			required: true,
			message: locales.getText("oauth.apple.identifier.required")
		}]
	}, /* @__PURE__ */ React.createElement(Input, { placeholder: locales.getText("oauth.apple.identifier.placeholder") }))), (currentProvider === null || currentProvider === void 0 ? void 0 : currentProvider.id) === "facebook" && /* @__PURE__ */ React.createElement(Form, {
		form,
		layout: "vertical"
	}, /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("oauth.facebook.appId"),
		name: "appid",
		rules: [{
			required: true,
			message: locales.getText("oauth.facebook.appId.required")
		}]
	}, /* @__PURE__ */ React.createElement(Input, { placeholder: locales.getText("oauth.facebook.appId.placeholder") })), /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("oauth.facebook.appSecret"),
		name: "secret_key",
		rules: [{
			required: true,
			message: locales.getText("oauth.facebook.appSecret.required")
		}]
	}, /* @__PURE__ */ React.createElement(Input.Password, { placeholder: locales.getText("oauth.facebook.appSecret.placeholder") })))), /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		gap: "8px",
		justifyContent: "flex-end",
		padding: "16px 0",
		borderTop: "1px solid #f0f0f0",
		marginTop: "auto"
	} }, /* @__PURE__ */ React.createElement(Button, { onClick: handleDrawerClose }, locales.getText("oauth.button.cancel")), /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		onClick: handleSaveSettings
	}, locales.getText("oauth.button.save"))))));
};
//#endregion
export { OAuthConfig as default };
