import { useEffect, useState } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { AlertCircle, Lock, User } from 'lucide-react'
import { useLogin, usePublicSite } from '@/api/hooks'
import { setAuthCache } from '@/lib/auth'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'

export default function Login() {
  const navigate = useNavigate()
  const loginMutation = useLogin()
  // 公开站点配置失败不影响登录页本身
  const { data: site } = usePublicSite()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')

  const title = site?.title || '任务池'
  const subtitle = site?.subtitle || '登录到管理面板'

  useEffect(() => {
    document.title = title
  }, [title])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    try {
      await loginMutation.mutateAsync({ username, password })
      setAuthCache(true)
      navigate({ to: '/' })
    } catch (err: any) {
      setError(err?.message || '登录失败')
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-[var(--bg-primary)] p-5 text-[var(--text-primary)]">
      <Card className="w-full max-w-md p-8">
        <div className="mb-8 text-center">
          <div className="ms-on-accent mx-auto mb-4 flex h-14 w-14 select-none items-center justify-center rounded-xl bg-[var(--bg-accent)] text-xl font-bold text-[var(--text-on-accent)] shadow-sm">
            T
          </div>
          <h1 className="mb-2 text-2xl font-semibold">{title}</h1>
          <p className="text-sm text-[var(--text-muted)]">{subtitle}</p>
        </div>

        {error && (
          <div className="mb-5 flex items-center gap-2 rounded-md bg-[color-mix(in_srgb,var(--danger)_14%,transparent)] px-3 py-2 text-sm text-[var(--danger)]">
            <AlertCircle size={16} strokeWidth={1.5} />
            <span>{error}</span>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">用户名</label>
            <div className="relative">
              <User size={16} strokeWidth={1.5} className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-muted)]" />
              <Input
                className="pl-10"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="请输入用户名"
                required
                autoComplete="username"
              />
            </div>
          </div>

          <div>
            <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">密码</label>
            <div className="relative">
              <Lock size={16} strokeWidth={1.5} className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-muted)]" />
              <Input
                className="pl-10"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="请输入密码"
                required
                autoComplete="current-password"
              />
            </div>
          </div>

          <Button type="submit" className="mt-2 w-full" disabled={loginMutation.isPending}>
            {loginMutation.isPending ? '登录中...' : '登录'}
          </Button>
        </form>
      </Card>
    </div>
  )
}
