import { useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { identity } from '@/api/client'
import { PageHeader } from '@/components/PageHeader'
import { ErrorBox } from '@/components/ErrorBox'

export function CreateUserPage() {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [displayName, setDisplayName] = useState('')
  const [email, setEmail] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<Error | null>(null)

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setSubmitting(true)
    try {
      const user = await identity.createUser({
        username, displayName, email: email || null,
      })
      navigate(`/users/${user.id}`)
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div>
      <PageHeader
        title="New User"
        subtitle="Create a user account. Assign roles on the detail page after creation."
        actions={<button className="btn-secondary" onClick={() => navigate('/users')}>Cancel</button>}
      />
      <form onSubmit={onSubmit} className="card p-6 space-y-4 max-w-lg">
        <div>
          <label className="block text-sm font-medium text-slate-700">Username</label>
          <input type="text" required value={username} onChange={(e) => setUsername(e.target.value)}
            placeholder="jdoe" className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700">Display name</label>
          <input type="text" required value={displayName} onChange={(e) => setDisplayName(e.target.value)}
            placeholder="Jane Doe" className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700">Email (optional)</label>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
            className="mt-1 w-full rounded-md border border-slate-300 px-3 py-2 text-sm" />
        </div>
        {error && <ErrorBox error={error} />}
        <button type="submit" className="btn-primary" disabled={submitting}>
          {submitting ? 'Creating...' : 'Create User'}
        </button>
      </form>
    </div>
  )
}
