// Copyright (c) 2025, JINGROW and contributors
// For license information, please see license.txt

const PAGETYPE = "Ai Settings"
const SECRET_FIELD = "jingrow_api_secret"
const EYE_CLASS = "ai-settings-secret-eye"

jingrow.ui.form.on(PAGETYPE, {
	onload(frm) {
		setupSecretEye(frm)
	},
	refresh(frm) {
		setupSecretEye(frm)
	},
})

function setupSecretEye(frm) {
	const field = frm.fields_dict?.[SECRET_FIELD]
	if (!field) {
		return
	}

	const isAdmin = jingrow.user.has_role("System Manager")
	const $inputWrapper = field.$wrapper?.find(".control-input")
	const $input = field.$input

	$inputWrapper?.find(`.${EYE_CLASS}`).remove()
	$inputWrapper?.css("position", "")
	$input?.css("padding-right", "")
	$input?.attr("type", "password")

	if (!isAdmin || !$inputWrapper?.length) {
		return
	}

	const state = {
		value: null,
		revealed: false,
		loading: false,
	}

	const $eye = $(
		`<span class="${EYE_CLASS}" title="${__("查看密钥")}">
			${jingrow.utils.icon("unhide", "sm")}
		</span>`
	)
		.css({
			position: "absolute",
			top: "50%",
			right: "10px",
			transform: "translateY(-50%)",
			cursor: "pointer",
			display: "inline-flex",
			"align-items": "center",
			"justify-content": "center",
			"pointer-events": "auto",
			"min-width": "18px",
		})
		.on("click", () => handleToggle(frm, field, state, $eye))

	$inputWrapper.css("position", "relative")
	$input?.css("padding-right", "30px")
	$inputWrapper.append($eye)
}

function handleToggle(frm, field, state, $eye) {
	if (state.loading) {
		return
	}

	if (state.revealed) {
		state.revealed = false
		field.$input.attr("type", "password")
		$eye.html(jingrow.utils.icon("unhide", "sm"))
		return
	}

	if (state.value) {
		showSecret(field, state, $eye)
		return
	}

	state.loading = true
	$eye.addClass("text-muted")

	jingrow.call({
		method: "jingrow.client.get_password",
		args: {
			pagetype: PAGETYPE,
			name: frm.pg?.name || PAGETYPE,
			fieldname: SECRET_FIELD,
		},
		callback: (r) => {
			state.loading = false
			$eye.removeClass("text-muted")
			const value = r.message
			if (!value) {
				jingrow.show_alert({
					message: __("未配置 Jingrow Api Secret"),
					indicator: "orange",
				})
				return
			}
			state.value = value
			showSecret(field, state, $eye)
		},
		error: () => {
			state.loading = false
			$eye.removeClass("text-muted")
		},
	})
}

function showSecret(field, state, $eye) {
	state.revealed = true
	field.$input.attr("type", "text").val(state.value)
	$eye.html(jingrow.utils.icon("hide", "sm"))
}

