// src/pages/Auth/EmailVerification.jsx
// Rublikák a kód beírásához, email ellenőrzéshez

import { useState, useRef, useEffect } from "react"
import Background from "../../assets/backgrounds/Background"
import { motion } from "framer-motion"
import Button from "../../components/Buttons/Button"
import { useLocation } from "react-router-dom"

export default function EmailVerification() {
  const [code, setCode] = useState(Array(6).fill(""))
  const inputRefs = useRef([])
  const location = useLocation()
  const [showSuccess, setShowSuccess] = useState(false)
  const [error, setError] = useState("")

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

  const handleChange = (e, index) => {
    const { value } = e.target
    if (/^\d*$/.test(value) && value.length <= 1) {
      const newCode = [...code]
      newCode[index] = value
      setCode(newCode)
      if (value && index < 5) {
        inputRefs.current[index + 1].focus()
      }
    }
  }

  const handleKeyDown = (e, index) => {
    if (e.key === "Backspace" && !code[index] && index > 0) {
      inputRefs.current[index - 1].focus()
    } else if (e.key === "ArrowLeft" && index > 0) {
      inputRefs.current[index - 1].focus()
    } else if (e.key === "ArrowRight" && index < 5) {
      inputRefs.current[index + 1].focus()
    } else if (/^\d$/.test(e.key) && code[index]) {
      e.preventDefault()
      const newCode = [...code]
      newCode[index] = e.key
      setCode(newCode)

      if (index < 5) {
        setTimeout(() => {
          inputRefs.current[index + 1].focus()
        }, 0)
      }
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError("")
    const token = code.join("")
    if (token.length !== 6) {
      setError("A kód 6 számjegyből áll.")
      return
    }
    try {
      const res = await fetch(`/verify-email/${token}`)
      const data = await res.json()
      if (data.success) {
        setShowSuccess(true)
        setTimeout(() => setShowSuccess(false), 2000)
      } else {
        setError(data.message || "Sikertelen ellenőrzés.")
      }
    } catch (err) {
      setError("Hiba történt az ellenőrzés során.")
    }
  }

  return (
    <div className="relative flex items-center justify-center min-h-screen bg-gray-100 p-0 font-poppins">
      <Background />
      {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 email ellenőrzés!
        </div>
      )}
      {error && (
        <div className="fixed top-20 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>
      )}
      <motion.div
        initial={{ height: "auto" }}
        animate={{ height: "300px" }}
        transition={{ duration: 0.5, ease: "easeInOut" }}
        className="absolute flex max-w-2xl w-full bg-white rounded-2xl shadow-lg overflow-hidden items-center justify-center"
      >
        <div className="w-full p-10 relative">
          <h2 className="text-4xl font-extrabold text-center mb-6 text-gray-800 tracking-wide">
            Email megerősítés
          </h2>
          <form onSubmit={handleSubmit}>
            <div className="mb-6 flex justify-center space-x-2">
              {code.map((digit, index) => (
                <input
                  key={index}
                  type="text"
                  value={digit}
                  onChange={(e) => handleChange(e, index)}
                  onKeyDown={(e) => handleKeyDown(e, index)}
                  ref={(el) => (inputRefs.current[index] = el)}
                  className={`w-12 h-12 px-2 py-3 border rounded-lg focus:ring-4 focus:ring-indigo-400 text-gray-700 placeholder-gray-400 bg-gray-50 text-center text-2xl tracking-widest ${
                    !digit ? "placeholder-opacity-100" : "placeholder-opacity-0"
                  }`}
                  // nem tudom, hogy hogyan jobb
                  // placeholder="_"
                  maxLength="1"
                />
              ))}
            </div>
            <Button text="Megerősít" type="submit" />
          </form>
        </div>
      </motion.div>
    </div>
  )
}
