'use client'
import { useState, Suspense } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { Leaf, Eye, EyeOff, AlertCircle } from 'lucide-react'
import { FontAwesomeIcon } from '@/lib/fa'
import styles from './page.module.css'

function RegisterForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const redirect = searchParams.get('redirect') ?? '/'

  const [form, setForm] = useState({ name: '', email: '', phone: '', password: '' })
  const [showPass, setShowPass] = useState(false)
  const [agreed, setAgreed] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const set = (k: string) => (e: React.ChangeEvent<HTMLInputElement>) => setForm(p => ({ ...p, [k]: e.target.value }))

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

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

      if (!res.ok) {
        setError(json.error ?? 'Pendaftaran gagal. Coba lagi.')
        return
      }

      // Redirect to intended destination after register (auto-login)
      router.push(redirect.startsWith('/') ? redirect : '/')
      router.refresh()
    } catch {
      setError('Tidak dapat terhubung ke server. Periksa koneksi internet Anda.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className={styles.page}>
      <div className={styles.card}>
        <div className={styles.logo}><Leaf size={20} strokeWidth={1.5}/><span>Kembali SPA</span></div>
        <h1 className={styles.title}>Buat Akun</h1>
        <p className={styles.subtitle}>
          Bergabung dan nikmati layanan spa premium
          <FontAwesomeIcon icon="leaf" style={{ marginLeft: 6, color: 'var(--sage-500)' }} aria-hidden="true" />
        </p>

        {/* Error */}
        {error && (
          <div className={styles.errorBox} role="alert">
            <AlertCircle size={16} aria-hidden="true" />
            <span>{error}</span>
          </div>
        )}

        <form onSubmit={handleSubmit} className={styles.form}>
          <div>
            <label className="input-label">Nama Lengkap</label>
            <input className="input" type="text" placeholder="Nama sesuai KTP" value={form.name} onChange={set('name')} required />
          </div>
          <div>
            <label className="input-label">Email</label>
            <input className="input" type="email" placeholder="hello@email.com" value={form.email} onChange={set('email')} required />
          </div>
          <div>
            <label className="input-label">Nomor HP</label>
            <input className="input" type="tel" placeholder="08xx-xxxx-xxxx" value={form.phone} onChange={set('phone')} required />
          </div>
          <div>
            <label className="input-label">Password</label>
            <div className={styles.passWrap}>
              <input
                className={`input ${styles.passInput}`}
                type={showPass ? 'text' : 'password'}
                placeholder="Min. 8 karakter"
                value={form.password}
                onChange={set('password')}
                minLength={8}
                required
              />
              <button type="button" className={styles.eyeBtn} onClick={() => setShowPass(!showPass)} aria-label={showPass ? 'Sembunyikan password' : 'Tampilkan password'}>
                {showPass ? <EyeOff size={16}/> : <Eye size={16}/>}
              </button>
            </div>
            <div className="input-helper">Min. 8 karakter</div>
          </div>
          <label className={styles.checkboxRow}>
            <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)} required />
            <span>Saya setuju dengan <Link href="/terms" className={styles.link}>Syarat &amp; Ketentuan</Link> dan <Link href="/privacy" className={styles.link}>Kebijakan Privasi</Link></span>
          </label>
          <button type="submit" className="btn btn-primary btn-full" disabled={loading || !agreed}>
            {loading ? (
              <><FontAwesomeIcon icon="hourglass-half" style={{ marginRight: 5 }} aria-hidden="true" />Memproses...</>
            ) : (
              'Daftar Sekarang'
            )}
          </button>
        </form>

        <p className={styles.loginText}>
          Sudah punya akun?{' '}
          <Link href={`/login${redirect !== '/' ? `?redirect=${encodeURIComponent(redirect)}` : ''}`} className={styles.loginLink}>
            Masuk
          </Link>
        </p>
      </div>
    </div>
  )
}

export default function RegisterPage() {
  return (
    <Suspense fallback={<div className="page-loader">Memuat...</div>}>
      <RegisterForm />
    </Suspense>
  )
}
