"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 };
}

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

	async function submit() {
		setError("");
		setIsSubmitting(true);
		try {
			const response = await fetch(`/api/claw/auth/${mode}`, {
				method: "POST",
				headers: { "content-type": "application/json" },
				body: JSON.stringify({ username, password }),
			});
			const payload = (await response.json()) as {
				account?: ClawAccount;
				error?: string;
			};
			if (!response.ok || !payload.account) {
				throw new Error(payload.error ?? "账号操作失败");
			}
			onAccount(payload.account);
		} catch (err) {
			setError(err instanceof Error ? err.message : "账号操作失败");
		} 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">
						中控数据开发平台会按账号隔离会话、上传文件和生成产物。
					</p>
				</div>
				<div className="grid gap-3">
					<Input
						autoFocus
						placeholder="账号"
						value={username}
						onChange={(event) => setUsername(event.target.value)}
						onKeyDown={(event) => {
							if (event.key === "Enter") submit();
						}}
					/>
					<Input
						type="password"
						placeholder="密码"
						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 === "login" ? "登录" : "注册"}
					</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>
	);
}
