import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useAuth } from '../lib/auth-context'
import { trpc } from '../lib/trpc-client'
import { p, MyButton, pInput, pButton } from 'web-components'

export const Route = createFileRoute('/register')({ component: RegisterPage })

function RegisterPage() {
  const { register: authRegister } = useAuth()
  const navigate = useNavigate()
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [mobile, setMobile] = useState('')
  const [password, setPassword] = useState('')

  const registerMutation = trpc.user.auth.register.useMutation({
    onSuccess: (data) => {
      if (data.token && data.user) {
        authRegister(data.token, data.user)
        navigate({ to: '/home' })
      }
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    registerMutation.mutate({ name, email, mobile, password })
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-brand-400 to-brand-700 p-4">
      <div className="w-full max-w-md">
        <p className="font-bold mb-2 text-center text-4xl text-white">
          Create Account
        </p>
        <p className="mb-8 text-center text-lg text-blue-100">
          Join Freshyo today
        </p>

        <div className="rounded-2xl bg-white p-8 shadow-xl">
          <form onSubmit={handleSubmit} className="flex flex-col gap-4">
            <pInput
              placeholder="Full Name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
            />
            <pInput
              placeholder="Email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <pInput
              placeholder="Mobile Number"
              value={mobile}
              onChange={(e) => {
                const clean = e.target.value.replace(/\D/g, '')
                if (clean.length <= 10) setMobile(clean)
              }}
              required
            />
            <pInput
              placeholder="Password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
            <MyButton
              type="submit"
              fullWidth
              className="mt-2 h-12 rounded-xl bg-brand-600 text-white shadow-lg"
              disabled={registerMutation.isPending}
              textContent={registerMutation.isPending ? 'Creating...' : 'Register'}
            />
          </form>
        </div>
      </div>
    </div>
  )
}
