import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { toast } from 'react-hot-toast'
import { useAuth } from '../context/useAuth.js'
import { Button } from '../components/Button.jsx'
import { Input } from '../components/Input.jsx'
import { PasswordInput } from '../components/PasswordInput.jsx'
import { FormCard } from '../components/FormCard.jsx'
import { Alert } from '../components/Alert.jsx'

export default function RegisterPage() {
  const { register } = useAuth()
  const navigate = useNavigate()

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState(null)

  const validate = () => {
    if (!username.trim()) return 'Username is required'
    if (username.trim().length < 3) return 'Username must be at least 3 characters'
    if (!password.trim()) return 'Password is required'
    if (password.length < 6) return 'Password must be at least 6 characters'
    return null
  }

  const onSubmit = async (e) => {
    e.preventDefault()
    const v = validate()
    if (v) {
      setError(v)
      return
    }

    setError(null)
    setSubmitting(true)
    try {
      await register({ username: username.trim(), password })
      toast.success('Account created. Please login.')
      navigate('/login', { replace: true })
    } catch (err) {
      setError(err?.message || 'Registration failed')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="min-h-screen px-4 py-10">
      <div className="mx-auto max-w-lg">
        <div className="mb-6 text-center">
          <h1 className="text-2xl font-bold text-slate-900">Create your account</h1>
          <p className="mt-2 text-sm text-slate-600">Register to start managing your supply chain workflow.</p>
        </div>

        <FormCard title="Register" description="Create a new user account.">
          {error ? <Alert type="error" message={error} /> : null}

          <form className="mt-5 space-y-4" onSubmit={onSubmit}>
            <Input label="Username" value={username} onChange={setUsername} placeholder="Choose a username" />
            <PasswordInput label="Password" value={password} onChange={setPassword} />
            <Button type="submit" disabled={submitting} className="w-full">
              {submitting ? <span className="inline-flex items-center gap-2"><span className="h-4 w-4 animate-spin rounded-full border-2 border-white/60 border-t-white" /> Creating…</span> : 'Create Account'}
            </Button>
          </form>

          <div className="mt-5 text-center text-sm text-slate-600">
            Already have an account?{' '}
            <Link className="font-medium text-slate-900 hover:underline" to="/login">Login</Link>
          </div>
        </FormCard>
      </div>
    </div>
  )
}

