// src/pages/Auth/LoginForm.jsx
import InputBox from "../../components/Inputs/InputBox"
import Button from "../../components/Buttons/Button"
import { motion } from "framer-motion"
import { useState, useEffect } from "react"
import { useLocation, useNavigate } from "react-router-dom"
import { login } from "../../api/userApi"
import { FaArrowLeft } from "react-icons/fa"

export default function LoginForm() {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [error, setError] = useState("")
  const location = useLocation()
  const navigate = useNavigate()
  const [showSuccess, setShowSuccess] = useState(false)
  const [showErrorPopup, setShowErrorPopup] = useState(false)

  useEffect(() => {
    if (location.state && location.state.success) {
      setShowSuccess(true)
      setTimeout(() => setShowSuccess(false), 4000)
    }
  }, [location.state])

  function validateEmail(email) {
    return /\S+@\S+\.\S+/.test(email)
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    setError("")
    setShowErrorPopup(false)

    if (!email || !password) {
      setError("Minden mező kitöltése kötelező.")
      setShowErrorPopup(true)
      setTimeout(() => setShowErrorPopup(false), 2000)
      return
    }

    if (!validateEmail(email)) {
      setError("Hibás email formátum.")
      setShowErrorPopup(true)
      setTimeout(() => setShowErrorPopup(false), 2000)
      return
    }

    login(email, password)
      .then((response) => {
        if (response && response.status === 200) {
          if (response.data && response.data.user) {
            localStorage.setItem("username", response.data.user.username)
            localStorage.setItem("authLevel", response.data.user.authLevel)
          }
          navigate("/home")
        } else {
          setError("Hibás bejelentkezési adatok.")
          setShowErrorPopup(true)
          setTimeout(() => setShowErrorPopup(false), 2000)
        }
      })
      .catch(() => {
        setError("Hibás bejelentkezési adatok.")
        setShowErrorPopup(true)
        setTimeout(() => setShowErrorPopup(false), 2000)
      })
  }

  return (
    <motion.div
      key="login"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.25 }}
      className="relative flex flex-col items-center"
    >
      {/* 🔙 Vissza nyíl gomb — most pontosan a fehér box bal felső sarkában */}
      <div
        className="absolute -top-6 -left-6 flex items-center group cursor-pointer select-none"
        onClick={() => navigate("/")}
      >
        <FaArrowLeft className="text-gray-700 text-xl transition-transform duration-300 group-hover:-translate-x-1" />
        <span className="ml-2 text-gray-700 font-medium opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all duration-300">
          Vissza a főoldalra
        </span>
      </div>

      <h2 className="text-4xl font-extrabold text-center mb-6 text-gray-800 tracking-wide">
        Bejelentkezés
      </h2>

      {showSuccess && (
        <div className="fixed top-6 left-1/2 -translate-x-1/2 bg-green-500 text-white px-6 py-2 rounded shadow-lg z-50 text-center font-semibold transition-opacity duration-300">
          Sikeres regisztráció! Az email ellenőrzése után be tudsz lépni.
        </div>
      )}

      {showErrorPopup && error && (
        <div className="fixed top-6 left-1/2 -translate-x-1/2 bg-red-500 text-white px-6 py-2 rounded shadow-lg z-50 text-center font-semibold transition-opacity duration-300">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        <InputBox
          type="email"
          placeholder="Email cím"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <InputBox
          type="password"
          placeholder="Jelszó"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <Button text="Bejelentkezés" type="submit" />
      </form>
    </motion.div>
  )
}
