<template>
	<div class="h-screen overflow-hidden sm:bg-gray-50">
		<LoginBox title="登录到您在 Jingrow 上的站点" :subtitle="subtitle">
			<template v-slot:default>
				<div>
					<div v-if="sitePrePicked">
						<div v-if="loginError">
							<div class="flex items-center justify-center space-x-2 text-base">
								<FeatherIcon name="alert-triangle" class="mr-2 h-4 w-4" />
								<p>
									尝试登录您的站点时出错了
								</p>
							</div>
							<div class="mx-4 mt-4 space-x-4">
								<Button
									label="重试"
									icon-left="refresh-cw"
									:loading="login.loading"
									@click="loginToSite(pickedSite)"
								/>
								<Button
									label="查看您的站点"
									icon-left="list"
									:route="{
										name: 'Site Login',
									}"
								/>
							</div>
						</div>
						<div
							v-else-if="isPickedSiteValid"
							class="mt-8 flex flex-col items-center justify-center space-x-2 text-base"
						>
							<div class="flex items-center justify-center space-x-2 text-base">
								<FeatherIcon name="alert-circle" class="mr-2 h-4 w-4" />
								<div>
									<p>您即将登录到您的站点</p>
									<span class="font-semibold">{{ pickedSiteDomain }}</span>
								</div>
							</div>
							<div class="mx-4 mt-8 space-x-4">
								<Button
									label="登录"
									icon-left="log-in"
									variant="solid"
									:loading="login.loading"
									@click="loginToSite(pickedSite)"
								/>
							</div>
						</div>
					</div>
					<div
						v-else-if="
							$session.loading || isCookieValid.loading || sites.loading
						"
						class="mx-auto flex items-center justify-center space-x-2 text-base"
					>
						<LoadingText />
					</div>
					<form v-else-if="!sites.fetched">
						<FormControl
							label="邮箱"
							:disabled="showOTPField"
							class="w-full"
							v-model="email"
							placeholder="johndoe@mail.com"
						/>
						<FormControl
							v-if="showOTPField"
							label="验证码"
							v-model="otp"
							placeholder="123456"
							class="mt-2"
						/>
						<div v-if="showOTPField">
							<Button
								label="验证"
								:disabled="otp.length !== 6"
								:loading="
									sites.loading ||
									sendOTPMethod.loading ||
									verifyOTPMethod.loading
								"
								variant="solid"
								class="mt-4 w-full"
								@click="verifyOTP"
							/>
							<Button
								variant="outline"
								class="mt-2 w-full"
								:disabled="otpResendCountdown > 0"
								@click="sendOTP()"
								:loading="sendOTPMethod.loading"
							>
								重新发送验证码
								{{
									otpResendCountdown > 0
										? `在 ${otpResendCountdown} 秒后`
										: ''
								}}
							</Button>
						</div>
						<Button
							v-else
							label="提交"
							:disabled="email.length === 0"
							:loading="
								sites.loading ||
								sendOTPMethod.loading ||
								verifyOTPMethod.loading
							"
							variant="solid"
							class="mt-4 w-full"
							@click="sendOTP"
						/>
					</form>
					<div v-else-if="pickedSite">
						<div
							class="mt-8 flex items-center justify-center space-x-2 text-base"
						>
							<FeatherIcon name="alert-triangle" class="mr-2 h-4 w-4" />
							<div class="flex flex-col gap-2">
								<p>
									{{ email || session.user }} 不是站点
									<span class="font-semibold">{{ pickedSite }}</span>
									的用户
								</p>
							</div>
						</div>
						<div class="mt-8 flex w-full justify-center space-x-4">
							<Button
								label="查看您的站点"
								icon-left="list"
								@click="
									() => {
										$router.push({
											name: 'Site Login',
										});
}
								"
							/>
						</div>
					</div>
					<div v-else class="mt-10">
						<div v-if="sites.data.length === 0">
							<div class="text-center text-base leading-6 text-gray-700">
								<div>未找到 {{ email }} 的站点</div>
								<Link :to="{ name: 'Signup' }">注册</Link> 以创建新站点
							</div>
						</div>
						<div class="space-y-2" v-else>
							<div
								v-for="site in sites.data"
								:key="site.name"
								class="flex items-center justify-between rounded-md px-3 py-2 hover:cursor-pointer hover:bg-gray-100"
								@click="loginToSite(site.name)"
							>
								<div
									class="flex min-h-[40px] w-full items-center justify-between"
								>
									<div class="space-y-2">
										<div class="text-base text-gray-800">
											{{ site.host_name || site.name }}
										</div>
									</div>
									<FeatherIcon name="external-link" class="h-4 w-4" />
								</div>
							</div>
						</div>
					</div>

					<ErrorMessage
						class="mt-4"
						:message="
							sites.error || sendOTPMethod.error || verifyOTPMethod.error
						"
					/>
				</div>
			</template>
			<template v-slot:footer>
				<div
					class="flex w-full flex-col items-center justify-center space-y-2 pb-8"
				>
					<Button
						v-if="sites.fetched"
						class="mt-4"
						@click="goBack"
						icon-right="log-out"
						variant="ghost"
						label="登出"
					/>
					<Button
						class="mt-4"
						@click="
							$router.push({
								name: 'Login',
							})
						"
						icon-right="arrow-right"
						variant="ghost"
						label="前往 Jingrow 仪表盘"
					/>
				</div>
			</template>
		</LoginBox>
	</div>
</template>

<script setup>
import { computed, inject, ref } from 'vue';
import { toast } from 'vue-sonner';
import { createResource } from 'jingrow-ui';
import LoginBox from '../components/auth/LoginBox.vue';
import { getToastErrorMessage } from '../utils/toast';
import { trialDays } from '../utils/site';
import { userCurrency } from '../utils/format';
import { useRoute } from 'vue-router';

const team = inject('team');
const session = inject('session');

const route = useRoute();
const pickedSite = computed(() => route.query.site);
const isPickedSiteValid = ref(false);

const email = ref(localStorage.getItem('product_site_user') || '');
const otp = ref('');
const showOTPField = ref(false);
const loginError = ref(false);
const otpResendCountdown = ref(0);

setInterval(() => {
	if (otpResendCountdown.value > 0) {
		otpResendCountdown.value -= 1;
	}
}, 1000);

const goBack = () => {
	sites.reset();
	showOTPField.value = false;
};

const isCookieValid = createResource({
	url: 'jcloud.api.site_login.check_session_id',
	auto: !session.user,
	onSuccess: (session_user_email) => {
		if (session_user_email) {
			email.value = session_user_email;
			sites.submit({
				user: session_user_email,
			});
		}
	},
});

const sites = createResource({
	url: 'jcloud.api.site_login.get_product_sites_of_user',
	pagetype: 'Site',
	auto: session.user,
	params: {
		user: email.value || session.user,
	},
	onSuccess: (data) => {
		if (pickedSite.value) {
			if (
				data.find((site) => site.name === pickedSite.value) ||
				data.find((site) => site.host_name === pickedSite.value)
			) {
				isPickedSiteValid.value = true;
			}
		}
	},
});

const login = createResource({
	url: 'jcloud.api.site_login.login_to_site',
	onSuccess: (url) => {
		const newTab = pickedSite.value ? '_self' : '_blank';
		window.open(url, newTab);
	},
});

function loginToSite(siteName) {
	if (!siteName) {
		toast.error('请选择一个站点');
		return;
	}

	// avoid toast if user is coming from their site to login
	if (pickedSite.value)
		login.submit({
email: email.value || session.user,
			site: siteName,
		});
	else
		toast.promise(
			login.submit({
				email: email.value || session.user,
				site: siteName,
			}),
			{
				loading: '登录中...',
				success: '登录成功',
				error: (e) => {
					loginError.value = true;
					getToastErrorMessage(e);
				},
			},
		);
}

const sendOTPMethod = createResource({
	url: 'jcloud.api.site_login.send_otp',
	onSuccess: () => {
		showOTPField.value = true;
		otpResendCountdown.value = 30;
		if (email.value) localStorage.setItem('site_login_email', email.value);
	},
});

function sendOTP() {
	if (!email.value) {
		toast.error('请输入邮箱');
		return;
	}

	toast.promise(
		sendOTPMethod.submit({
			email: email.value,
		}),
		{
			loading: '发送OTP中...',
			success: `OTP已发送至 ${email.value}`,
			error: (e) => getToastErrorMessage(e),
		},
	);
}

const verifyOTPMethod = createResource({
	url: 'jcloud.api.site_login.verify_otp',
	onSuccess: () => {
		sites.submit({
			user: email.value,
		});
		otp.value = '';
		sendOTPMethod.error = '';
	},
});

function verifyOTP() {
	if (!otp.value) {
		toast.error('请输入OTP');
		return;
	}

	toast.promise(
		verifyOTPMethod.submit({
			email: email.value,
			otp: otp.value,
		}),
		{
			loading: '验证OTP中...',
			success: 'OTP验证成功',
			error: (e) => getToastErrorMessage(e),
		},
	);
}

function planTitle(site) {
	if (site.trial_end_date) return trialDays(site.trial_end_date);
	if (site.price_usd > 0 && team) {
		const china = team?.pg?.currency === 'CNY';
		const formattedValue = userCurrency(
			china ? site.price_cny : site.price_usd,
			0,
		);
		return `${formattedValue}/月`;
	}
	return site.plan_title;
}

const subtitle = computed(() => {
	if (pickedSite.value && sites.fetched && sites.data.length !== 0) return '';
	else if (sites.fetched && sites.data.length !== 0)
		return `选择要登录的站点，以 ${email.value || session.user} 身份登录`;
	else if (
		!sites.fetched &&
		!(sites.loading || isCookieValid.loading || session.loading)
	)
		return '输入您的邮箱以访问您的站点';
	else return '';
});

const sitePrePicked = computed(() => {
	if (pickedSite.value && sites.fetched && sites.data.length !== 0) {
		return sites.data.find(
			(site) =>
				site.name === pickedSite.value || site.host_name === pickedSite.value,
		);
	}
	return false;
});

const pickedSiteDomain = computed(() => {
	if (sitePrePicked.value)
		return sitePrePicked.value.host_name || sitePrePicked.value.name;
	return '';
});
</script>