// src/pages/Auth/RegisterForm.jsx
import InputBox from "../../components/Inputs/InputBox"
import Button from "../../components/Buttons/Button"
import { motion } from "framer-motion"
import { useState } from "react"
import { register } from "../../api/userApi"
import { useNavigate, useLocation } from "react-router-dom"
import { ToastConfig } from "../../components/Toastify/toastifyServices"
import { FaArrowLeft } from "react-icons/fa"

export default function RegisterForm() {
  const [lastname, setLastname] = useState("")
  const [firstname, setFirstname] = useState("")
  const [username, setUsername] = useState("")
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [phone, setPhone] = useState("")
  const [error, setError] = useState("")
  const [showErrorPopup, setShowErrorPopup] = useState(false)
  const navigate = useNavigate()
  const location = useLocation()

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

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

    if (!lastname || !firstname || !username || !email || !password || !confirmPassword || !phone) {
      setError("Minden mező kitöltése kötelező.")
      return
    }
    if (!validateEmail(email)) {
      setError("Hibás email formátum.")
      return
    }
    if (password.length < 6) {
      setError("A jelszónak legalább 6 karakter hosszúnak kell lennie.")
      return
    }
    if (password !== confirmPassword) {
      setError("A jelszavak nem egyeznek.")
      return
    }

    try {
      const response = await register(username, email, password, firstname, lastname, phone)
      if (response && response.status === 201) {
        ToastConfig("✅ Sikeres regisztráció!")
        if (location.pathname === "/login") {
          navigate("/login", { state: { success: true } })
          window.location.reload()
        } else {
          navigate("/login", { state: { success: true } })
        }
      } else {
        let msg = "Sikertelen regisztráció."
        if (response?.data?.error) msg = response.data.error
        setError(msg)
        setShowErrorPopup(true)
        setTimeout(() => setShowErrorPopup(false), 2000)
      }
    } catch (err) {
      let msg = err?.response?.data?.error || err.message || "Ismeretlen hiba történt."
      setError(msg)
      setShowErrorPopup(true)
      setTimeout(() => setShowErrorPopup(false), 2000)
    }
  }

  return (
    <motion.div
      key="register"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.25 }}
      className="relative flex flex-col items-center"
    >
      {/* 🔙 Vissza nyíl gomb – ugyanott, mint a login oldalon */}
      <div
        className="absolute -top-2 -left-1 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">
        Regisztráció
      </h2>

      {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="text" placeholder="Vezetéknév" value={lastname} onChange={(e) => setLastname(e.target.value)} />
        <InputBox type="text" placeholder="Keresztnév" value={firstname} onChange={(e) => setFirstname(e.target.value)} />
        <InputBox type="text" placeholder="Felhasználónév" value={username} onChange={(e) => setUsername(e.target.value)} />
        <InputBox type="email" placeholder="Email cím" value={email} onChange={(e) => setEmail(e.target.value)} />
        <InputBox type="phone" placeholder="Telefonszám" value={phone} onChange={(e) => setPhone(e.target.value)} />
        <InputBox type="password" placeholder="Jelszó" value={password} onChange={(e) => setPassword(e.target.value)} />
        <InputBox type="password" placeholder="Jelszó megerősítése" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} />
        <Button text="Regisztráció" type="submit" />
      </form>
    </motion.div>
  )
}
