import { useEffect, useState } from 'react'
import { Link, Navigate, useNavigate } from 'react-router-dom'
import { useAuth } from '../auth/AuthContext'
import { ApiError } from '../api/client'
import { AuthShell } from '../components/AuthShell'
import { Button, ErrorText, Field, Input } from '../components/ui'

export function LoginPage() {
  const { login, setTenantId, isAuthenticated } = useAuth()
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    setTenantId('default')
  }, [setTenantId])

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

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      await login(email, password)
      navigate('/')
    } catch (err) {
      setError(err instanceof ApiError ? err.message : '登入失敗')
    } finally {
      setLoading(false)
    }
  }

  return (
    <AuthShell tagline="歡迎回來，島民！">
      <div className="auth-shell-body">
        <p className="auth-shell-lead text-ink-secondary">
          輸入帳號密碼，就能開始今天的<span className="font-bold text-brand">巡樓任務</span>。
        </p>
        <form className="auth-shell-form space-y-5" onSubmit={onSubmit}>
          <Field label="Email">
            <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
          </Field>
          <Field label="Password">
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </Field>
          <ErrorText message={error} />
          <Button type="submit" disabled={loading} className="w-full">
            {loading ? '登入中…' : '登入'}
          </Button>
        </form>
        <p className="auth-shell-footer text-center text-ink-secondary">
          還沒有帳號？{' '}
          <Link className="font-semibold text-brand hover:underline" to="/register">
            前往註冊
          </Link>
        </p>
      </div>
    </AuthShell>
  )
}