import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import client, { TOKEN_KEY } from '../api/client.ts'

export default function Login() {
  const nav = useNavigate()
  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('')
  const [err, setErr] = useState('')
  const [loading, setLoading] = useState(false)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setErr('')
    setLoading(true)
    try {
      const { data } = await client.post('/login', { username, password })
      localStorage.setItem(TOKEN_KEY, data.token)
      nav('/', { replace: true })
    } catch (e: any) {
      setErr(e?.response?.data?.error || '登录失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div
      style={{
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <form className="card" style={{ width: 340 }} onSubmit={submit}>
        <h2 style={{ marginTop: 0 }}>🥕 CarrotAssistant</h2>
        <div className="field">
          <label>用户名</label>
          <input value={username} onChange={(e) => setUsername(e.target.value)} autoFocus />
        </div>
        <div className="field">
          <label>密码</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        {err && <div style={{ color: 'var(--danger)', marginBottom: 10 }}>{err}</div>}
        <button className="primary" style={{ width: '100%' }} disabled={loading}>
          {loading ? '登录中…' : '登录'}
        </button>
      </form>
    </div>
  )
}
