import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-hot-toast'
import { useAuthStore } from '../context/authStore'
import { validateAuthFields } from '../utils/validators'

export default function RegisterPage() {
  const navigate = useNavigate()
  const { register, isAuthenticated, loading } = useAuthStore()

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [errors, setErrors] = useState({})
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    if (isAuthenticated && !loading) navigate('/dashboard', { replace: true })
  }, [isAuthenticated, loading, navigate])

  const handleSubmit = async (e) => {
    e.preventDefault()

    const nextErrors = validateAuthFields({ username, password })
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

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

  return (
    <div className="min-h-[100svh] flex items-center justify-center px-4 bg-slate-700">
      <div className="w-full max-w-md rounded-2xl border border-white/10 bg-white/5 backdrop-blur p-6 shadow-xl">
        <div className="flex items-center gap-3 mb-5">
          <div className="h-10 w-10 rounded-xl bg-gradient-to-br from-purple-500 to-fuchsia-500 flex items-center justify-center text-white font-bold">
            SH
          </div>
          <div>
            <h1 className="text-2xl font-semibold text-white">StockHub</h1>
            <p className="text-sm text-white/70">Create your account</p>
          </div>
        </div>

        <h2 className="text-xl font-semibold text-white mb-1">Register</h2>
        <p className="text-sm text-white/70 mb-6">Sign up to manage products, warehouses and stock transactions.</p>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-white/80 mb-1">Username</label>
            <input
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-white placeholder:text-white/40 outline-none focus:border-fuchsia-400/60"
              placeholder="Enter username"
              autoComplete="username"
            />
            {errors.username ? <p className="text-xs text-red-400 mt-1">{errors.username}</p> : null}
          </div>

          <div>
            <label className="block text-sm font-medium text-white/80 mb-1">Password</label>
            <input
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              type="password"
              className="w-full rounded-xl border border-white/10 bg-black/20 px-3 py-2 text-white placeholder:text-white/40 outline-none focus:border-fuchsia-400/60"
              placeholder="Enter password"
              autoComplete="new-password"
            />
            {errors.password ? <p className="text-xs text-red-400 mt-1">{errors.password}</p> : null}
          </div>

          <button
            type="submit"
            disabled={submitting}
            className="w-full rounded-xl bg-gradient-to-r from-purple-500 to-fuchsia-500 text-white py-2.5 font-semibold shadow-lg hover:opacity-95 disabled:opacity-60 disabled:cursor-not-allowed transition"
          >
            {submitting ? 'Creating...' : 'Register'}
          </button>

          <div className="text-center text-sm text-white/70">
            Already have an account?{' '}
            <button type="button" onClick={() => navigate('/login')} className="text-fuchsia-300 hover:underline">
              Login
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

