import { useState } from 'react'
import { useAuth } from '../auth/AuthContext'
import { api, ApiError } from '../api/client'
import { Button, ErrorText, Field, Input, Notice } from './ui'

type RegisterFormProps = {
  onBack?: () => void
  backLabel?: string
  onSuccess?: (email: string) => void
}

export function RegisterForm({ onBack, backLabel = '返回登入', onSuccess }: RegisterFormProps) {
  const { tenantId } = useAuth()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [displayName, setDisplayName] = useState('')
  const [error, setError] = useState('')
  const [successEmail, setSuccessEmail] = useState('')
  const [loading, setLoading] = useState(false)

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setSuccessEmail('')
    setLoading(true)
    try {
      await api.post('/api/v1/auth/register', {
        tenant_id: tenantId,
        email,
        password,
        display_name: displayName,
        language: 'zh-TW',
      })
      const createdEmail = email
      setEmail('')
      setPassword('')
      setDisplayName('')
      setSuccessEmail(createdEmail)
      onSuccess?.(createdEmail)
    } catch (err) {
      setError(err instanceof ApiError ? err.message : '註冊失敗')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="auth-shell-body">
      <p className="auth-shell-lead text-ink-secondary">
        建立新帳號後，對方可用 Email 與密碼自行登入；你不會被切換登出。
      </p>

      {successEmail ? (
        <Notice
          tone="success"
          title="帳號已建立"
          message={`${successEmail} 已建立完成，請通知對方至登入頁登入。`}
        />
      ) : null}

      <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>
      {onBack ? (
        <p className="auth-shell-footer text-center text-ink-secondary">
          <button
            type="button"
            className="font-semibold text-brand hover:underline"
            onClick={onBack}
          >
            {backLabel}
          </button>
        </p>
      ) : null}
    </div>
  )
}