// src/app/(auth)/register/page.tsx
'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Select } from '@/components/ui/Select'

export default function RegisterPage() {
  const router = useRouter()
  const [form, setForm] = useState({
    name: '',
    surname: '',
    email: '',
    password: '',
    role: 'JOB_SEEKER',
  })
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [globalError, setGlobalError] = useState('')
  const [loading, setLoading] = useState(false)

  function update(field: string, value: string) {
    setForm((f) => ({ ...f, [field]: value }))
    setErrors((e) => ({ ...e, [field]: '' }))
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setGlobalError('')
    setLoading(true)

    try {
      const res = await fetch('/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })

      const data = await res.json()

      if (!res.ok) {
        if (data.issues) {
          const fieldErrors: Record<string, string> = {}
          for (const [field, msgs] of Object.entries(data.issues as Record<string, string[]>)) {
            fieldErrors[field] = msgs[0] ?? 'Invalid'
          }
          setErrors(fieldErrors)
        } else {
          setGlobalError(data.error ?? 'Registration failed. Please try again.')
        }
        return
      }

      router.push('/login?registered=1')
    } catch {
      setGlobalError('Something went wrong. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-neutral-50 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="flex justify-center mb-8">
          <Link href="/" className="flex items-center gap-2">
            <span className="h-10 w-10 bg-brand-600 rounded-xl flex items-center justify-center">
              <svg className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            </span>
            <span className="text-2xl font-bold text-neutral-900" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
              Motif
            </span>
          </Link>
        </div>

        <div className="card p-8">
          <div className="mb-6">
            <h1 className="text-2xl font-bold text-neutral-900" style={{ fontFamily: 'Space Grotesk, sans-serif' }}>
              Create your account
            </h1>
            <p className="text-neutral-500 mt-1 text-sm">Join Motif — it&apos;s free</p>
          </div>

          {globalError && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700">
              {globalError}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <Input
                label="First name"
                id="register-name"
                value={form.name}
                onChange={(e) => update('name', e.target.value)}
                placeholder="Amara"
                error={errors.name}
                required
              />
              <Input
                label="Surname"
                id="register-surname"
                value={form.surname}
                onChange={(e) => update('surname', e.target.value)}
                placeholder="Nkosi"
                error={errors.surname}
                required
              />
            </div>
            <Input
              label="Email address"
              type="email"
              id="register-email"
              value={form.email}
              onChange={(e) => update('email', e.target.value)}
              placeholder="you@example.com"
              error={errors.email}
              required
            />
            <Input
              label="Password"
              type="password"
              id="register-password"
              value={form.password}
              onChange={(e) => update('password', e.target.value)}
              placeholder="Min 8 chars, 1 uppercase, 1 number"
              error={errors.password}
              hint="Minimum 8 characters, include uppercase and a number"
              required
            />
            <Select
              label="I am a..."
              id="register-role"
              value={form.role}
              onChange={(e) => update('role', e.target.value)}
              options={[
                { value: 'JOB_SEEKER', label: 'Job Seeker' },
                { value: 'EMPLOYER', label: 'Employer / Hiring Manager' },
                { value: 'SERVICE_PROVIDER', label: 'Service Provider / Freelancer' },
              ]}
            />
            <Button type="submit" loading={loading} className="w-full" size="lg">
              Create account
            </Button>
          </form>

          <p className="text-center text-sm text-neutral-500 mt-6">
            Already have an account?{' '}
            <Link href="/login" className="text-brand-600 font-semibold hover:underline">
              Sign in
            </Link>
          </p>
        </div>
      </div>
    </div>
  )
}
