"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { ArrowRightIcon, EnvelopeIcon, LockClosedIcon, EyeIcon, EyeSlashIcon, ExclamationTriangleIcon } from "@heroicons/react/24/outline"
import { login } from "@/services/authService"

export default function LoginForm() {
  const router = useRouter()
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)
  const [fieldErrors, setFieldErrors] = useState<{ email?: string; password?: string }>({})

  const validate = () => {
    const errors: { email?: string; password?: string } = {}
    if (!email) {
      errors.email = "Email is required"
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      errors.email = "Enter a valid email"
    }
    if (!password) {
      errors.password = "Password is required"
    } else if (password.length < 6) {
      errors.password = "Must be at least 6 characters"
    }
    setFieldErrors(errors)
    return Object.keys(errors).length === 0
  }

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    setErrorMessage(null)
    if (!validate()) return

    setIsSubmitting(true)
    try {
      const result = await login(email, password)
      const token = result?.token ?? result?.data?.token
      if (token) {
        localStorage.setItem("token", token)
      }
      router.push("/")
    } catch (error: any) {
      const message = error?.response?.data?.message || error?.message || "Failed to sign in"
      setErrorMessage(message)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <>
      {errorMessage && (
        <div className="mt-5 flex items-start gap-2 rounded-md border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-200" role="alert" aria-live="polite">
          <ExclamationTriangleIcon className="h-5 w-5 flex-shrink-0" />
          <span>{errorMessage}</span>
        </div>
      )}

      <form onSubmit={handleSubmit} className="mt-6 space-y-5" noValidate>
        <div className="relative">
          <label htmlFor="email" className="mb-2 block text-xs font-medium text-gray-300 tracking-wide">
            Email
          </label>
          <EnvelopeIcon className="pointer-events-none absolute left-3 top-10 h-5 w-5 text-gray-400" />
          <input
            id="email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            autoComplete="email"
            className={`input-field ${fieldErrors.email ? "border-red-500/40 focus:border-red-500/60 focus:ring-red-500/30" : ""}`}
            placeholder="you@example.com"
            aria-invalid={!!fieldErrors.email}
            aria-describedby={fieldErrors.email ? "email-error" : undefined}
          />
          {fieldErrors.email && (
            <p id="email-error" className="mt-2 text-xs text-red-300">{fieldErrors.email}</p>
          )}
        </div>

        <div className="relative">
          <label htmlFor="password" className="mb-2 block text-xs font-medium text-gray-300 tracking-wide">
            Password
          </label>
          <LockClosedIcon className="pointer-events-none absolute left-3 top-10 h-5 w-5 text-gray-400" />
          <input
            id="password"
            type={showPassword ? "text" : "password"}
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            autoComplete="current-password"
            className={`input-field pr-11 ${fieldErrors.password ? "border-red-500/40 focus:border-red-500/60 focus:ring-red-500/30" : ""}`}
            placeholder="••••••••"
            aria-invalid={!!fieldErrors.password}
            aria-describedby={fieldErrors.password ? "password-error" : undefined}
          />
          <button
            type="button"
            onClick={() => setShowPassword((v) => !v)}
            className="absolute right-3 top-9 rounded-md p-1 text-gray-400 hover:text-gray-200 focus:outline-none"
            aria-label={showPassword ? "Hide password" : "Show password"}
          >
            {showPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
          </button>
          {fieldErrors.password && (
            <p id="password-error" className="mt-2 text-xs text-red-300">{fieldErrors.password}</p>
          )}
        </div>

        <button type="submit" disabled={isSubmitting} className="btn-gradient w-full">
          {isSubmitting ? (
            <span className="inline-flex items-center gap-2">
              <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
              </svg>
              Signing in…
            </span>
          ) : (
            <span className="inline-flex items-center gap-2">
              Sign in
              <ArrowRightIcon className="h-4 w-4" />
            </span>
          )}
        </button>
      </form>
    </>
  )
}
