import { useState } from "react";
import { Link } from "react-router";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../components/ui/card";
import { useAuth } from "../../hooks/useAuth";

export function LoginPage() {
  const { login, loginPending, loginError } = useAuth();
  const [form, setForm] = useState({ email: "", password: "" });
  const [formError, setFormError] = useState<string | null>(null);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const email = form.email.trim();
    const password = form.password.trim();

    if (!email || !password) {
      setFormError("请输入邮箱和密码");
      return;
    }

    setFormError(null);
    login({ email, password });
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-4">
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl">Dramix</CardTitle>
          <CardDescription>登录您的账号</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4" noValidate>
            <div className="space-y-2">
              <Label htmlFor="email">邮箱</Label>
              <Input
                id="email"
                type="email"
                placeholder="you@example.com"
                required
                value={form.email}
                onChange={(e) => {
                  setFormError(null);
                  setForm((f) => ({ ...f, email: e.target.value }));
                }}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">密码</Label>
              <Input
                id="password"
                type="password"
                placeholder="••••••••"
                required
                value={form.password}
                onChange={(e) => {
                  setFormError(null);
                  setForm((f) => ({ ...f, password: e.target.value }));
                }}
              />
            </div>

            {(formError || loginError) && (
              <p className="text-sm text-destructive">
                {formError ?? (loginError instanceof Error ? loginError.message : "登录失败")}
              </p>
            )}

            <Button type="submit" className="w-full" disabled={loginPending}>
              {loginPending ? "登录中..." : "登录"}
            </Button>

            <p className="text-center text-sm text-muted-foreground">
              没有账号？{" "}
              <Link to="/register" className="text-primary underline-offset-4 hover:underline">
                立即注册
              </Link>
            </p>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
