import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
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, Spin, Typography, message } from "antd";
import { locales } from "@pisell/utils";
import { AppleOutlined, FacebookOutlined } from "@ant-design/icons";
import "./CustomerOAuthConfig.less";
//#region src/components/authentication/admin/CustomerOAuthConfig/index.tsx
const { Title, Paragraph } = Typography;
const CustomerOAuthConfig = ({ 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 [loading, setLoading] = useState(true);
	const [drawerOpen, setDrawerOpen] = useState(false);
	const [currentProvider, setCurrentProvider] = useState(null);
	const [tenantId, setTenantId] = useState(null);
	const initialProviders = [{
		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 [providers, setProviders] = useState(initialProviders);
	useEffect(() => {
		console.log("app_init_customer_oauth_config", app, context, data.storage);
	}, []);
	useEffect(() => {
		const coreData = data.storage.getStorage("core");
		console.log("coreData from storage:", coreData);
		if (coreData) try {
			var _coreDataJson$tenant;
			const coreDataJson = JSON.parse(coreData);
			console.log("parsed coreDataJson:", coreDataJson);
			if (coreDataJson === null || coreDataJson === void 0 || (_coreDataJson$tenant = coreDataJson.tenant) === null || _coreDataJson$tenant === void 0 ? void 0 : _coreDataJson$tenant.id) {
				console.log("setting tenantId:", coreDataJson.tenant.id);
				setTenantId(coreDataJson.tenant.id);
			} else console.log("tenant.id not found in coreData");
		} catch (error) {
			console.error("Error parsing core data:", error);
		}
		else console.log("No coreData found in storage");
	}, [data.storage]);
	const checkAllProvidersStatus = function() {
		var _ref2 = _asyncToGenerator(function* () {
			console.log("checkAllProvidersStatus called, tenantId:", tenantId);
			if (!tenantId) {
				console.log("No tenantId, skipping status check");
				setLoading(false);
				return;
			}
			setLoading(true);
			console.log("Starting to check providers status...");
			const updatedProviders = yield Promise.all(initialProviders.map(function() {
				var _ref = _asyncToGenerator(function* (provider) {
					const dataKey = `auth.oauth.${provider.id}`;
					console.log(`Checking ${provider.id} with dataKey:`, dataKey);
					try {
						var _res$data, _res$data$;
						const url = `/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`;
						console.log(`Requesting URL:`, url);
						const res = yield request.get(url);
						console.log(`check_status_${provider.id}`, res);
						let hasConfig = false;
						if ((res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.length) > 0 && ((_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.value)) {
							const configData = res.data[0].value;
							console.log(`${provider.id} configData:`, configData);
							if (typeof configData === "object" && configData !== null) {
								const hasValidValue = Object.values(configData).some((val) => val !== null && val !== void 0 && val !== "");
								hasConfig = hasValidValue;
								console.log(`${provider.id} hasValidValue:`, hasValidValue);
							} else hasConfig = !!configData;
						}
						console.log(`${provider.id} hasConfig:`, hasConfig);
						return _objectSpread2(_objectSpread2({}, provider), {}, { configured: hasConfig });
					} catch (error) {
						console.error(`Error checking ${provider.id} status:`, error);
						return _objectSpread2(_objectSpread2({}, provider), {}, { configured: false });
					}
				});
				return function(_x) {
					return _ref.apply(this, arguments);
				};
			}()));
			console.log("Updated providers:", updatedProviders);
			setProviders(updatedProviders);
			setLoading(false);
		});
		return function checkAllProvidersStatus() {
			return _ref2.apply(this, arguments);
		};
	}();
	useEffect(() => {
		console.log("tenantId useEffect triggered, tenantId:", tenantId);
		if (tenantId) {
			console.log("tenantId is valid, calling checkAllProvidersStatus");
			checkAllProvidersStatus();
		} else console.log("tenantId is null or undefined");
	}, [tenantId]);
	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 renderMethodTitle = (method) => {
		const getStatusTag = () => {
			if (method.enabled) return null;
			return /* @__PURE__ */ React.createElement("span", { style: _objectSpread2(_objectSpread2({}, {
				display: "inline-block",
				padding: "2px 8px",
				borderRadius: "4px",
				fontSize: "12px",
				fontWeight: 500,
				lineHeight: "20px"
			}), {}, {
				backgroundColor: "#fff7e6",
				color: "#fa8c16",
				border: "1px solid #ffd591"
			}) }, locales.getText("oauth.status.not.configured"));
		};
		return /* @__PURE__ */ React.createElement("div", { style: {
			display: "flex",
			alignItems: "center",
			gap: "8px"
		} }, /* @__PURE__ */ React.createElement("span", null, method.title), getStatusTag());
	};
	const loadProviderConfig = function() {
		var _ref3 = _asyncToGenerator(function* (providerId) {
			if (!tenantId) {
				console.log("No tenantId, cannot load provider config");
				return;
			}
			const dataKey = `auth.oauth.${providerId}`;
			console.log(`Loading config for ${providerId} with dataKey:`, dataKey);
			try {
				var _res$data2, _res$data$2;
				const url = `/tenant/core/meta?key=${dataKey}&metable_type=tenant&metable_id=${tenantId}`;
				console.log(`Loading from URL:`, url);
				const res = yield request.get(url);
				console.log(`load_config_${providerId}`, res);
				if ((res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.length) > 0 && ((_res$data$2 = res.data[0]) === null || _res$data$2 === void 0 ? void 0 : _res$data$2.value)) {
					const configData = res.data[0].value;
					console.log(`${providerId} loaded configData:`, configData);
					if (configData && typeof configData === "object") {
						form.setFieldsValue(configData);
						console.log("Form fields set with:", configData);
					}
				} else {
					console.log(`No config data found for ${providerId}`);
					form.resetFields();
				}
			} catch (error) {
				console.error(`Error loading ${providerId} config:`, error);
				form.resetFields();
			}
		});
		return function loadProviderConfig(_x2) {
			return _ref3.apply(this, arguments);
		};
	}();
	const handleSettings = function() {
		var _ref4 = _asyncToGenerator(function* (method) {
			console.log("handleSettings called for method:", method);
			const provider = providers.find((p) => p.id === method.id);
			console.log("Found provider:", provider);
			if (provider) {
				setCurrentProvider(provider);
				setDrawerOpen(true);
				yield loadProviderConfig(provider.id);
			}
		});
		return function handleSettings(_x3) {
			return _ref4.apply(this, arguments);
		};
	}();
	const handleDrawerClose = () => {
		setDrawerOpen(false);
		setCurrentProvider(null);
		form.resetFields();
	};
	const handleSaveSettings = function() {
		var _ref5 = _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 };
				else if (currentProvider.id === "google") configData = {
					clientId: values.clientId,
					clientSecret: values.clientSecret
				};
				console.log("Saving to API:", {
					dataKey,
					configData
				});
				yield request.post(`/tenant/core/meta/tenant/${tenantId}`, { [dataKey]: configData });
				message.success(locales.getText("oauth.save.success") || "保存成功");
				yield checkAllProvidersStatus();
				handleDrawerClose();
			} catch (error) {
				console.error("Validation failed or save error:", error);
				message.error(locales.getText("oauth.save.error") || "保存失败");
			}
		});
		return function handleSaveSettings() {
			return _ref5.apply(this, arguments);
		};
	}();
	if (loading) return /* @__PURE__ */ React.createElement("div", {
		className: `customer-oauth-config ${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: `customer-oauth-config ${className || ""}`,
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "customer-oauth-config-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 1,
		className: "customer-oauth-config-title"
	}, locales.getText("oauth.config.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "customer-oauth-config-description" }, locales.getText("oauth.config.description"))), /* @__PURE__ */ React.createElement("div", { className: "customer-oauth-config-section" }, /* @__PURE__ */ React.createElement("div", { className: "customer-oauth-config-section-layout" }, /* @__PURE__ */ React.createElement("div", { className: "customer-oauth-config-section-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 2,
		className: "customer-oauth-config-section-title"
	}, locales.getText("oauth.providers.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "customer-oauth-config-section-description" }, locales.getText("oauth.providers.description"))), /* @__PURE__ */ React.createElement("div", { className: "customer-oauth-config-section-content" }, /* @__PURE__ */ React.createElement(SettingList, {
		methods: authMethods,
		onSettings: handleSettings,
		enableSetting: true,
		renderTitle: renderMethodTitle
	})))), /* @__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 { CustomerOAuthConfig as default };
