import { useEffect, useState, useRef } from "react";
import { useLocation } from "react-router-dom";
import Background from "../../assets/backgrounds/Background";
import { notifySuccess, notifyError } from "../../components/Toastify/toastifyServices";
import { verifyEmail } from "../../api/userApi";
import HandleNavigate from "../../utils/HandleNavigate/HandleNavigate";

export default function VerifyEmailPage() {
  const { goLogin } = HandleNavigate();
  const location = useLocation();
  const [status, setStatus] = useState("loading");
  const [message, setMessage] = useState("Email címe hitelesítés alatt...");
  const hasNotified = useRef(false);

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    const token = queryParams.get("token");

    if (!token) {
      setStatus("error");
      setMessage("Hiányzó hitelesítő token!");
      if (!hasNotified.current) {
        notifyError("❌ Hiányzó hitelesítő token!");
        hasNotified.current = true;
      }
      return;
    }

    const verify = async () => {
      try {
        const response = await verifyEmail(token);
        const data = response.data;

        if (data?.success) {
          setStatus("success");
          setMessage("Sikeres hitelesítés!");
          if (!hasNotified.current) {
            notifySuccess("✅ Email címe sikeresen hitelesítve!");
            hasNotified.current = true;
          }
          setTimeout(() => goLogin(), 2500);
        } else {
          throw new Error(data?.message || "Sikertelen hitelesítés");
        }
      } catch (err) {
        setStatus("error");
        setMessage("Sikertelen hitelesítés. Kérjük, vegye fel velünk a kapcsolatot!");
        if (!hasNotified.current) {
          notifyError("❌ Sikertelen hitelesítés!");
          hasNotified.current = true;
        }
      }
    };

    verify();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.search]);

  return (
    <div className="w-full min-h-screen flex items-center justify-center relative overflow-hidden">
      <div className="fixed inset-0 -z-10">
        <Background />
      </div>

      <div className="bg-white/10 backdrop-blur-lg p-10 rounded-2xl shadow-lg text-center border border-white/20 max-w-md">
        {status === "loading" && (
          <div className="flex flex-col items-center gap-3 text-white">
            <div className="w-10 h-10 border-4 border-white border-t-transparent rounded-full animate-spin"></div>
            <p className="text-lg font-semibold">{message}</p>
          </div>
        )}

        {status === "success" && (
          <div className="flex flex-col items-center gap-3 text-green-300">
            <span className="text-4xl">✅</span>
            <p className="text-lg font-semibold">{message}</p>
            <p className="text-sm text-gray-200">Átirányítás a bejelentkezéshez...</p>
          </div>
        )}

        {status === "error" && (
          <div className="flex flex-col items-center gap-3 text-red-300">
            <span className="text-4xl">❌</span>
            <p className="text-lg font-semibold text-center">{message}</p>
            <p className="text-sm text-gray-200">support@serpentrace.hu</p>
          </div>
        )}
      </div>
    </div>
  );
}
