import { useState } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { useAuth } from '../auth/AuthContext'

function extractToken(value: string): string {
  try {
    if (value.includes('token=')) {
      const url = new URL(value)
      return url.searchParams.get('token') || value
    }
  } catch {}
  return value
}

export function Register() {
  const { register } = useAuth()
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const [username, setUsername] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [inviteToken, setInviteToken] = useState(searchParams.get('token') || '')
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)
    setError(null)
    try {
      await register(username, email, password, inviteToken)
      navigate('/')
    } catch (err) {
      setError(err instanceof Error ? err.message : "Erreur d'inscription")
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center px-4">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <span className="text-5xl">🍷</span>
          <h1 className="font-display text-3xl font-bold text-cellar-gold mt-3">Cellar</h1>
          <p className="text-cellar-muted mt-1">Créez votre compte</p>
        </div>

        <form onSubmit={handleSubmit} className="card p-6 space-y-4">
          {error && (
            <div className="bg-red-900/30 border border-red-800 text-red-300 px-4 py-2 rounded-lg text-sm">
              {error}
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-1">Token d'invitation</label>
            <input
              type="text"
              value={inviteToken}
              onChange={(e) => setInviteToken(extractToken(e.target.value))}
              placeholder="Collez votre lien d'invitation"
              className="input-field"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-1">Nom d'utilisateur</label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="input-field"
              required
              autoFocus
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-1">Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="input-field"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-1">Mot de passe</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="input-field"
              required
              minLength={8}
              autoComplete="new-password"
            />
          </div>

          <button type="submit" disabled={submitting} className="btn-primary w-full disabled:opacity-50">
            {submitting ? 'Création...' : "S'inscrire"}
          </button>
        </form>

        <p className="text-center text-cellar-muted text-sm mt-4">
          Déjà un compte ?{' '}
          <Link to="/login" className="text-cellar-gold hover:text-cellar-gold-light transition-colors">
            Se connecter
          </Link>
        </p>
      </div>
    </div>
  )
}
