'use client'

import { useState, FormEvent } from 'react'
import { signIn } from 'next-auth/react'
import { useSearchParams } from 'next/navigation'
import Link from 'next/link'
import { motion } from 'framer-motion'
import { Button } from '@/components/ui/Button'

const ERROR_MESSAGES: Record<string, string> = {
  CredentialsSignin: 'Email ou password incorretos',
}

function getErrorMessage(error: string | null): string | null {
  if (!error) return null
  return ERROR_MESSAGES[error] ?? 'Ocorreu um erro. Tenta de novo.'
}

export default function LoginForm() {
  const searchParams = useSearchParams()
  const errorParam = searchParams.get('error')

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [runtimeError, setRuntimeError] = useState<string | null>(null)

  const displayError = runtimeError ?? getErrorMessage(errorParam)

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setRuntimeError(null)
    setLoading(true)

    try {
      const result = await signIn('credentials', {
        email,
        password,
        callbackUrl: '/',
        redirect: false,
      })

      if (result?.error) {
        setRuntimeError(getErrorMessage(result.error))
      } else if (result?.url) {
        window.location.href = result.url
      }
    } catch {
      setRuntimeError('Ocorreu um erro. Tenta de novo.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <motion.div
      className="auth-card"
      initial={{ opacity: 0, y: 24 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4, ease: [0.22, 0.61, 0.36, 1] }}
    >
      <div className="auth-logo">
        <img
          src="/brand/png/ondevoar-simbolo-azul.png"
          alt="OndeVoar"
          width={56}
          height={56}
        />
      </div>

      <h2 className="auth-heading">Entrar na tua conta</h2>

      {displayError && (
        <div className="auth-error" role="alert">
          {displayError}
        </div>
      )}

      <form className="auth-form" onSubmit={handleSubmit} noValidate>
        <div className="form-group">
          <label className="form-label" htmlFor="email">
            Email
          </label>
          <input
            id="email"
            type="email"
            name="email"
            className="form-input"
            autoComplete="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={loading}
            placeholder="o-teu@email.com"
          />
        </div>

        <div className="form-group">
          <label className="form-label" htmlFor="password">
            Password
          </label>
          <input
            id="password"
            type="password"
            name="password"
            className="form-input"
            autoComplete="current-password"
            required
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            disabled={loading}
            placeholder="A tua password"
          />
        </div>

        <div className="auth-submit">
          <Button
            type="submit"
            variant="primary"
            size="lg"
            loading={loading}
            disabled={loading}
            style={{ width: '100%' }}
          >
            Entrar
          </Button>
        </div>
      </form>

      <p className="auth-link">
        Ainda não tens conta?{' '}
        <Link href="/auth/register">Registar</Link>
      </p>
    </motion.div>
  )
}
