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 RegisterPage() {
  const { register, setTenantId, isAuthenticated } = useAuth()
  const navigate = useNavigate()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [displayName, setDisplayName] = 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 register({ email, password, displayName, language: 'zh-TW' })
      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="Display Name">
            <Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} />
          </Field>
          <Field label="Password（至少 8 字）">
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              minLength={8}
              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="/login">
            前往登入
          </Link>
        </p>
      </div>
    </AuthShell>
  )
}