"use client";

import { LogOutIcon } from "lucide-react";
import type { ReactNode } from "react";
import { useCallback, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { clearActiveSessionId } from "@/lib/claw-active-session";

export type ClawAccount = {
	id: string;
	username: string;
};

export function useClawAccount() {
	const [account, setAccount] = useState<ClawAccount | null>(null);
	const [isLoading, setIsLoading] = useState(true);

	const refresh = useCallback(async () => {
		setIsLoading(true);
		try {
			const response = await fetch("/api/claw/auth/me", { cache: "no-store" });
			const payload = (await response.json()) as {
				account?: ClawAccount | null;
			};
			setAccount(payload.account ?? null);
		} finally {
			setIsLoading(false);
		}
	}, []);

	useEffect(() => {
		refresh();
	}, [refresh]);

	return { account, isLoading, refresh, setAccount };
}

const XIAOMI_EMAIL_RE = /^[\w.-]+@xiaomi\.com$/i;

export function ClawAccountGate({
	onAccount,
}: {
	onAccount: (account: ClawAccount) => void;
}) {
	const [mode, setMode] = useState<"login" | "register">("login");
	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");
	const [error, setError] = useState("");
	const [isSubmitting, setIsSubmitting] = useState(false);

	async function submit() {
		setError("");
		const trimmed = email.trim();
		if (!XIAOMI_EMAIL_RE.test(trimmed)) {
			setError("请使用小米邮箱（@xiaomi.com）登录");
			return;
		}
		if (password.length < 6) {
			setError("密码至少 6 位");
			return;
		}
		setIsSubmitting(true);
		try {
			const endpoint =
				mode === "register"
					? "/api/claw/auth/email-register"
					: "/api/claw/auth/email-login";
			const response = await fetch(endpoint, {
				method: "POST",
				headers: { "content-type": "application/json" },
				body: JSON.stringify({ email: trimmed, password }),
			});
			const payload = (await response.json()) as {
				account?: ClawAccount;
				error?: string;
			};
			if (!response.ok || !payload.account) {
				throw new Error(
					payload.error ?? (mode === "register" ? "注册失败" : "登录失败"),
				);
			}
			onAccount(payload.account);
		} catch (err) {
			setError(
				err instanceof Error
					? err.message
					: mode === "register"
						? "注册失败"
						: "登录失败",
			);
		} finally {
			setIsSubmitting(false);
		}
	}

	return (
		<div className="flex min-h-dvh items-center justify-center bg-background px-4">
			<div className="w-full max-w-sm rounded-xl border bg-card p-6 shadow-sm">
				<div className="mb-6">
					<h1 className="font-semibold text-xl">ZK Data Agent</h1>
					<p className="mt-1 text-muted-foreground text-sm">
						{mode === "register"
							? "创建账号：使用小米邮箱注册，前缀作为 autoresearch 工作根目录。"
							: "使用小米邮箱登录。会话/上传/产物按邮箱前缀和 chat 二级隔离。"}
					</p>
				</div>
				<div className="grid gap-3">
					<Input
						autoFocus
						type="email"
						placeholder="your_name@xiaomi.com"
						value={email}
						onChange={(event) => setEmail(event.target.value)}
						onKeyDown={(event) => {
							if (event.key === "Enter") submit();
						}}
					/>
					<Input
						type="password"
						placeholder={mode === "register" ? "设置密码（≥6 位）" : "密码"}
						value={password}
						onChange={(event) => setPassword(event.target.value)}
						onKeyDown={(event) => {
							if (event.key === "Enter") submit();
						}}
					/>
					{error ? <p className="text-destructive text-sm">{error}</p> : null}
					<Button onClick={submit} disabled={isSubmitting}>
						{isSubmitting ? "处理中..." : mode === "register" ? "注册" : "登录"}
					</Button>
					<button
						type="button"
						className="text-muted-foreground text-sm hover:text-foreground"
						onClick={() => {
							setError("");
							setMode((current) =>
								current === "login" ? "register" : "login",
							);
						}}
					>
						{mode === "login" ? "没有账号，去注册" : "已有账号，去登录"}
					</button>
				</div>
			</div>
		</div>
	);
}

export function ClawAccountBar({
	account,
	onLogout,
	children,
}: {
	account: ClawAccount;
	onLogout: () => void;
	children: ReactNode;
}) {
	async function logout() {
		await fetch("/api/claw/auth/logout", { method: "POST" });
		clearActiveSessionId();
		onLogout();
	}

	return (
		<div className="ml-auto flex items-center gap-2">
			{children}
			<span className="max-w-32 truncate text-muted-foreground text-sm">
				{account.username}
			</span>
			<Button variant="ghost" size="icon" onClick={logout} title="退出登录">
				<LogOutIcon className="size-4" />
				<span className="sr-only">退出登录</span>
			</Button>
		</div>
	);
}
