"use client";

import { useState } from "react";
import { Mail, Loader2, CheckCircle2, ArrowLeft } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { authClient } from "@/lib/auth-client";

export default function LoginPage() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    const { error } = await authClient.signIn.magicLink({
      email,
      callbackURL: "/admin/uploads",
    });

    setLoading(false);

    if (error) {
      setError(error.message ?? "发送失败，请稍后重试");
      return;
    }

    setSent(true);
  }

  if (sent) {
    return (
      <div className="flex min-h-svh items-center justify-center bg-muted/50 p-4">
        <Card className="w-full max-w-sm">
          <CardHeader className="text-center">
            <div className="mx-auto mb-2 flex size-10 items-center justify-center rounded-lg bg-primary text-primary-foreground">
              <Mail className="size-5" />
            </div>
            <CardTitle className="text-xl">检查你的邮箱</CardTitle>
            <CardDescription>
              我们已向 <strong>{email}</strong> 发送了一封登录邮件
            </CardDescription>
          </CardHeader>
          <CardContent className="flex flex-col items-center gap-3 py-6 text-center">
            <CheckCircle2 className="size-10 text-emerald-500" />
            <p className="text-sm text-muted-foreground">
              点击邮件中的链接即可登录到管理后台。链接 5 分钟内有效。
            </p>
          </CardContent>
          <CardFooter className="flex flex-col gap-3">
            <Button
              variant="outline"
              className="w-full"
              onClick={() => {
                setSent(false);
                setEmail("");
              }}
            >
              <ArrowLeft className="size-4" />
              返回重新输入
            </Button>
          </CardFooter>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex min-h-svh items-center justify-center bg-muted/50 p-4">
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center">
          <div className="mx-auto mb-2 flex size-10 items-center justify-center rounded-lg bg-primary text-primary-foreground">
            <span className="text-sm font-bold">DX</span>
          </div>
          <CardTitle className="text-xl">登录</CardTitle>
          <CardDescription>
            输入邮箱，我们将发送登录链接到你的邮箱
          </CardDescription>
        </CardHeader>
        <form onSubmit={handleSubmit}>
          <CardContent className="grid gap-3">
            <div className="grid gap-2">
              <Label htmlFor="email">邮箱</Label>
              <Input
                id="email"
                type="email"
                placeholder="admin@dingxing.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                autoComplete="email"
              />
            </div>
            {error && (
              <p className="text-sm text-destructive" role="alert">
                {error}
              </p>
            )}
          </CardContent>
          <CardFooter className="flex flex-col gap-3">
            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  发送中...
                </>
              ) : (
                <>
                  <Mail className="size-4" />
                  发送登录链接
                </>
              )}
            </Button>
            <p className="text-center text-xs text-muted-foreground">
              无需密码，点击邮件中的链接即可登录
            </p>
          </CardFooter>
        </form>
      </Card>
    </div>
  );
}
