import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { trpc } from "@/lib/trpc";
import { useLocation } from "wouter";
import { toast } from "sonner";
import { Target, Loader2 } from "lucide-react";

export default function Login() {
  const [username, setUsername] = useState("");
  const [, setLocation] = useLocation();
  const utils = trpc.useUtils();
  const loginMutation = trpc.auth.loginWithUsername.useMutation();

  const syncAuthenticatedUser = async (fallbackUser: Awaited<ReturnType<typeof loginMutation.mutateAsync>>["user"]) => {
    // Seed the cache immediately so protected routes do not bounce back to /login.
    utils.auth.me.setData(undefined, fallbackUser);

    for (let attempt = 0; attempt < 3; attempt++) {
      const user = await utils.auth.me.fetch();
      if (user) {
        utils.auth.me.setData(undefined, user);
        return user;
      }
      await new Promise(resolve => window.setTimeout(resolve, 120 * (attempt + 1)));
    }

    return fallbackUser;
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!username.trim()) {
      toast.error("请输入用户名");
      return;
    }

    try {
      const data = await loginMutation.mutateAsync({ username: username.trim() });
      const user = await syncAuthenticatedUser(data.user);
      toast.success(data.isNew ? `欢迎加入，${user.name}！` : `欢迎回来，${user.name}！`);
      setLocation("/dashboard");
    } catch (err) {
      const message = err instanceof Error ? err.message : "未知错误";
      toast.error("登录失败: " + message);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-green-50 via-background to-emerald-50 p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-primary/10 mb-4">
            <Target className="w-8 h-8 text-primary" />
          </div>
          <h1 className="text-3xl font-bold tracking-tight">Tennis Hub</h1>
          <p className="text-muted-foreground mt-2">训练与分析入口</p>
        </div>

        <Card className="border-0 shadow-xl">
          <CardHeader className="text-center pb-2">
            <CardTitle className="text-xl" data-testid="login-title">登录</CardTitle>
            <CardDescription>输入用户名后进入系统</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleLogin} className="space-y-4">
              <div className="space-y-2">
                <Input
                  data-testid="login-username-input"
                  type="text"
                  placeholder="请输入您的用户名"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  className="h-12 text-base"
                  autoFocus
                  maxLength={64}
                />
              </div>
              <Button
                data-testid="login-submit-button"
                type="submit"
                className="w-full h-12 text-base font-medium"
                disabled={loginMutation.isPending || !username.trim()}
              >
                {loginMutation.isPending ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    登录中...
                  </>
                ) : (
                  "进入训练"
                )}
              </Button>
            </form>

            <div className="mt-6 pt-4 border-t">
              <div className="grid grid-cols-3 gap-3 text-center text-xs text-muted-foreground">
                <div className="flex flex-col items-center gap-1">
                  <div className="w-8 h-8 rounded-lg bg-primary/5 flex items-center justify-center text-primary font-bold text-sm">AI</div>
                  <span>姿势识别</span>
                </div>
                <div className="flex flex-col items-center gap-1">
                  <div className="w-8 h-8 rounded-lg bg-primary/5 flex items-center justify-center text-primary font-bold text-sm">📊</div>
                  <span>训练计划</span>
                </div>
                <div className="flex flex-col items-center gap-1">
                  <div className="w-8 h-8 rounded-lg bg-primary/5 flex items-center justify-center text-primary font-bold text-sm">🎯</div>
                  <span>NTRP评分</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <p className="text-center text-xs text-muted-foreground mt-6">
          输入用户名后进入系统
        </p>
      </div>
    </div>
  );
}
