'use client'

import { Suspense, useState } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { useAuth } from '@/lib/auth'
import type { ApiError } from '@/lib/api'

function LoginForm() {
  const router = useRouter()
  const params = useSearchParams()
  const login = useAuth((s) => s.login)
  const [credential, setCredential] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null); setBusy(true)
    try {
      await login(credential, password)
      router.push(params.get('redirect') || '/account')
    } catch (err) {
      setError((err as ApiError).message || 'Login failed.')
      setBusy(false)
    }
  }

  return (
    <div className="container-x flex justify-center py-12">
      <div className="card w-full max-w-md p-6">
        <h1 className="text-xl font-bold">Sign in</h1>
        <p className="mt-1 text-sm text-muted">Welcome back to Fitorza.</p>
        <form onSubmit={submit} className="mt-5 space-y-3">
          <input className="input" placeholder="Email or phone" value={credential} onChange={(e) => setCredential(e.target.value)} />
          <input className="input" type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />
          {error && <p className="text-sm text-rose-600">{error}</p>}
          <button disabled={busy} className="btn btn-primary w-full disabled:opacity-60">{busy ? 'Signing in…' : 'Sign in'}</button>
        </form>
        <div className="mt-4 flex justify-between text-sm">
          <Link href="/forgot-password" className="text-muted hover:underline">Forgot password?</Link>
          <Link href="/register" className="font-semibold text-brand-strong hover:underline">Create account</Link>
        </div>
      </div>
    </div>
  )
}

export default function LoginPage() {
  return <Suspense><LoginForm /></Suspense>
}
