'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 LoginForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const redirect = searchParams.get('redirect') ?? '/'

  const [identifier, setIdentifier] = useState('')
  const [password, setPassword] = useState('')
  const [showPass, setShowPass] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

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

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

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

      // Redirect to intended destination after 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}>Masuk ke Akun</h1>
        <p className={styles.subtitle}>
          Selamat datang kembali!
          <FontAwesomeIcon icon="leaf" style={{ marginLeft: 6, color: 'var(--sage-500)' }} aria-hidden="true" />
        </p>

        {/* Info redirect */}
        {redirect !== '/' && redirect !== '' && (
          <div className={styles.redirectNote}>
            <FontAwesomeIcon icon="circle-check" style={{ marginRight: 6, color: 'var(--sage-500)' }} aria-hidden="true" />
            Silakan login untuk melanjutkan ke halaman booking
          </div>
        )}

        {/* 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">Email atau No. HP</label>
            <input
              className="input"
              type="text"
              placeholder="hello@email.com / 08xx..."
              value={identifier}
              onChange={e => setIdentifier(e.target.value)}
              autoComplete="username"
              required
            />
          </div>
          <div>
            <label className="input-label">Password</label>
            <div className={styles.passWrap}>
              <input
                className={`input ${styles.passInput}`}
                type={showPass ? 'text' : 'password'}
                placeholder="••••••••"
                value={password}
                onChange={e => setPassword(e.target.value)}
                autoComplete="current-password"
                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>
          <div className={styles.forgotRow}>
            <Link href="/forgot-password" className={styles.forgotLink}>Lupa password?</Link>
          </div>
          <button type="submit" className="btn btn-primary btn-full" disabled={loading || !identifier || !password}>
            {loading ? (
              <><FontAwesomeIcon icon="hourglass-half" style={{ marginRight: 5 }} aria-hidden="true" />Memproses...</>
            ) : (
              'Masuk'
            )}
          </button>
        </form>

        <div className={styles.divider}><span>atau</span></div>
        <p className={styles.registerText}>
          Belum punya akun?{' '}
          <Link href={`/register${redirect !== '/' ? `?redirect=${encodeURIComponent(redirect)}` : ''}`} className={styles.registerLink}>
            Daftar sekarang
          </Link>
        </p>
      </div>
    </div>
  )
}

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