// 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 } from "react-router-dom"
import HandleNavigate from "../../utils/HandleNavigate/HandleNavigate"
import { login, forgotPassword } 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 { goHome, goLanding } = HandleNavigate()
  const [showSuccess, setShowSuccess] = useState(false)
  const [showErrorPopup, setShowErrorPopup] = useState(false)
  const [showForgotPasswordModal, setShowForgotPasswordModal] = useState(false)
  const [forgotEmail, setForgotEmail] = useState("")
  const [forgotPasswordMessage, setForgotPasswordMessage] = useState("")
  const [successMessage, setSuccessMessage] = useState("")
  const [isSendingEmail, setIsSendingEmail] = useState(false)

  useEffect(() => {
    if (location.state && location.state.success) {
      const message = location.state.message || "Sikeres regisztráció! Az email ellenőrzése után be tudsz lépni."
      setSuccessMessage(message)
      setShowSuccess(true)
      setTimeout(() => {
        setShowSuccess(false)
        setSuccessMessage("")
      }, 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)
          }
          goHome()
        } 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)
      })
  }

  const handleForgotPassword = async (e) => {
    e.preventDefault()
    setForgotPasswordMessage("")
    
    if (!forgotEmail || !validateEmail(forgotEmail)) {
      setForgotPasswordMessage("Kérlek adj meg egy érvényes email címet!")
      return
    }

    setIsSendingEmail(true)
    
    try {
      await forgotPassword(forgotEmail)
      setForgotPasswordMessage("Jelszó visszaállító email elküldve! Ellenőrizd a postaládád.")
      setTimeout(() => {
        setShowForgotPasswordModal(false)
        setForgotEmail("")
        setForgotPasswordMessage("")
        setIsSendingEmail(false)
      }, 3000)
    } catch (error) {
      setForgotPasswordMessage("Hiba történt. Próbáld újra később!")
      setIsSendingEmail(false)
    }
  }

  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={() => goLanding()}
      >
        <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">
          {successMessage || "Sikeres művelet!"}
        </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-4 w-full">
        <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)}
        />
        
        {/* Elfelejtett jelszó link */}
        <div className="text-right -mt-2">
          <span
            onClick={() => setShowForgotPasswordModal(true)}
            className="text-sm text-green-600 hover:text-green-700 hover:underline cursor-pointer font-medium"
          >
            Elfelejtetted a jelszavad?
          </span>
        </div>

        <Button text="Bejelentkezés" type="submit" />
      </form>

      {/* Forgot Password Modal */}
      {showForgotPasswordModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowForgotPasswordModal(false)}>
          <div className="bg-white rounded-xl shadow-2xl p-8 w-96 max-w-full" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-2xl font-bold text-gray-800 mb-4">Jelszó visszaállítás</h3>
            <p className="text-gray-600 mb-6 text-sm">
              Add meg az email címed és küldünk egy jelszó visszaállító linket.
            </p>
            
            <form onSubmit={handleForgotPassword} className="space-y-4">
              <InputBox
                type="email"
                placeholder="Email cím"
                value={forgotEmail}
                onChange={(e) => setForgotEmail(e.target.value)}
              />
              
              {forgotPasswordMessage && (
                <div className={`text-sm p-3 rounded ${forgotPasswordMessage.includes("elküldve") ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"}`}>
                  {forgotPasswordMessage}
                </div>
              )}

              <div className="flex gap-3">
                <button
                  type="submit"
                  disabled={isSendingEmail}
                  className={`flex-1 px-4 py-2 rounded-lg font-semibold transition-colors ${
                    isSendingEmail
                      ? 'bg-gray-400 text-gray-200 cursor-not-allowed'
                      : 'bg-[color:var(--color-mint)] text-white hover:opacity-90'
                  }`}
                >
                  {isSendingEmail ? 'Küldés...' : 'Küldés'}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setShowForgotPasswordModal(false)
                    setForgotEmail("")
                    setForgotPasswordMessage("")
                    setIsSendingEmail(false)
                  }}
                  className="flex-1 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors font-semibold"
                >
                  Mégse
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </motion.div>
  )
}
