import { useState, useEffect, type FormEvent } from "react"
import { useNavigate, Navigate, Link } from "react-router-dom"
import { toast } from "sonner"
import { Loader2Icon, ArrowLeftIcon } from "lucide-react"
import ThemeToggle from "@/components/ThemeToggle"
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { useAuthStore, isAdminRole } from "@/store/authStore"
import { login } from "@/api/auth"
import { setBaseUrl } from "@/api/client"
import { getErrorMessage } from "@/lib/errors"

export default function LoginPage() {
  const navigate = useNavigate()
  const token = useAuthStore((s) => s.token)
  const role = useAuthStore((s) => s.role)
  const setAuth = useAuthStore((s) => s.setAuth)

  const [serverUrl, setServerUrl] = useState("")
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    setServerUrl(localStorage.getItem("api_base_url") || "")
  }, [])

  if (token) {
    return <Navigate to={isAdminRole(role) ? "/admin/books" : "/books"} replace />
  }

  function validate(): boolean {
    const next: Record<string, string> = {}
    if (!serverUrl.trim()) next.serverUrl = "服务器地址不能为空"
    if (!username.trim()) next.username = "用户名不能为空"
    if (!password) next.password = "密码不能为空"
    setErrors(next)
    return Object.keys(next).length === 0
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault()
    if (!validate()) return

    setLoading(true)
    try {
      setBaseUrl(serverUrl.trim())
      const result = await login({ username: username.trim(), password })
      setAuth(result)
      toast.success("登录成功")
      navigate(isAdminRole(result.role) ? "/admin/books" : "/books", { replace: true })
    } catch (err) {
      toast.error(getErrorMessage(err, "登录失败"))
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-4 relative">
      <div className="absolute top-4 left-4">
        <Button variant="ghost" size="icon-sm" asChild>
          <Link to="/books">
            <ArrowLeftIcon className="size-4" />
          </Link>
        </Button>
      </div>
      <div className="absolute top-4 right-4">
        <ThemeToggle />
      </div>
      <Card className="w-full max-w-md mx-4 sm:mx-auto">
        <CardHeader>
          <CardTitle className="text-center text-xl">图书管理系统</CardTitle>
        </CardHeader>
        <form onSubmit={handleSubmit}>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="serverUrl">服务器地址</Label>
              <Input
                id="serverUrl"
                type="url"
                placeholder="http://localhost:8080"
                value={serverUrl}
                onChange={(e) => setServerUrl(e.target.value)}
                aria-invalid={!!errors.serverUrl}
              />
              {errors.serverUrl && (
                <p className="text-sm text-destructive">{errors.serverUrl}</p>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="username">用户名</Label>
              <Input
                id="username"
                placeholder="用户名"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                aria-invalid={!!errors.username}
              />
              {errors.username && (
                <p className="text-sm text-destructive">{errors.username}</p>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">密码</Label>
              <Input
                id="password"
                type="password"
                placeholder="密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                aria-invalid={!!errors.password}
              />
              {errors.password && (
                <p className="text-sm text-destructive">{errors.password}</p>
              )}
            </div>
          </CardContent>
          <CardFooter>
            <Button type="submit" className="w-full" disabled={loading}>
              {loading && <Loader2Icon className="animate-spin" />}
              {loading ? "登录中..." : "登录"}
            </Button>
          </CardFooter>
        </form>
      </Card>
    </div>
  )
}
