'use client'

import type { FormEvent } from 'react'
import { useEffect, useState } from 'react'
import { djangoUrl } from '@/lib/site-content'

export function LoginForm() {
  const [message, setMessage] = useState('')
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    if (!message) return
    const timer = window.setTimeout(() => setMessage(''), 6000)
    return () => window.clearTimeout(timer)
  }, [message])

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setMessage('')
    setSubmitting(true)

    try {
      const csrfResponse = await fetch(djangoUrl('/csrf/'), { cache: 'no-store', credentials: 'include', headers: { Accept: 'application/json' } })
      const csrfPayload = await csrfResponse.json().catch(() => null) as { csrfToken?: string } | null
      if (!csrfResponse.ok || !csrfPayload?.csrfToken) throw new Error('The sign-in service is unavailable. Please try again.')

      const formData = new FormData(event.currentTarget)
      const response = await fetch(djangoUrl('/api/auth/login/'), {
        method: 'POST',
        credentials: 'include',
        headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrfPayload.csrfToken },
        body: JSON.stringify({ email: String(formData.get('email') || ''), password: String(formData.get('password') || '') }),
      })
      const payload = await response.json().catch(() => null) as { detail?: string; redirectUrl?: string } | null
      if (!response.ok) {
        setMessage(payload?.detail || 'Email or password is incorrect.')
        return
      }
      window.location.assign(payload?.redirectUrl || '/dashboard/')
    } catch (error) {
      setMessage(error instanceof Error ? error.message : 'We could not connect to the sign-in service.')
    } finally {
      setSubmitting(false)
    }
  }

  return <form onSubmit={handleSubmit} className="mt-8 flex flex-col gap-5" noValidate>
    {message && <p role="alert" className="rounded-2xl border border-[var(--news-red)]/30 bg-[var(--news-red)]/10 px-4 py-3 text-sm font-semibold text-[var(--news-red)]">{message}</p>}
    <label className="text-sm font-semibold">Email address<input className="form-input" name="email" type="email" placeholder="you@example.com" autoComplete="email" required /></label>
    <label className="text-sm font-semibold">Password<input className="form-input" name="password" type="password" placeholder="Enter your password" autoComplete="current-password" required /></label>
    <button className="rounded-full bg-[var(--navy)] px-5 py-3.5 text-sm font-bold text-white disabled:cursor-wait disabled:opacity-60" type="submit" disabled={submitting}>{submitting ? 'Signing in…' : 'Sign in'}</button>
  </form>
}
