import { useState, type FormEvent } from 'react'
import { Navigate, useNavigate } from 'react-router-dom'
import { getToken } from '@/api/client'
import { login } from '@/api/auth'
import { LogoMark } from '@/components/logo'

export default function LoginPage() {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  if (getToken()) return <Navigate to="/" replace />

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      await login(username, password)
      navigate('/')
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-6">
      <form
        onSubmit={onSubmit}
        className="w-full max-w-[360px] rounded-xl border border-hairline bg-surface p-8"
      >
        <p className="mb-1 flex items-center gap-2 font-mono text-[13px] font-semibold">
          <LogoMark size={22} />
          sundynix <em className="not-italic text-accent">admin</em>
        </p>
        <h1 className="mb-6 text-[20px] font-[650] tracking-[-0.01em]">
          登录内容管理
        </h1>

        <label className="mb-4 block">
          <span className="mb-1.5 block text-[13px] text-ink-2">用户名</span>
          <input
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            autoComplete="username"
            required
            className="w-full rounded-lg border border-hairline-strong bg-ground px-3.5 py-2 text-[14.5px] outline-none transition-colors focus:border-accent"
          />
        </label>

        <label className="mb-5 block">
          <span className="mb-1.5 block text-[13px] text-ink-2">密码</span>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
            required
            className="w-full rounded-lg border border-hairline-strong bg-ground px-3.5 py-2 text-[14.5px] outline-none transition-colors focus:border-accent"
          />
        </label>

        {error && (
          <p className="mb-4 text-[13px] text-red-600 dark:text-red-400">
            {error}
          </p>
        )}

        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-lg bg-accent py-2.5 text-[14.5px] font-medium text-ground transition-opacity hover:opacity-90 disabled:opacity-60"
        >
          {loading ? '登录中…' : '登录'}
        </button>
      </form>
    </div>
  )
}
