"use client";
import React, { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Swal from "sweetalert2";
import { useDispatch } from "react-redux";
import { verifyEmailToken } from "@/app/redux/services/auth/authServices";

const EmailVerificationPage = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useDispatch();
  const [verificationStatus, setVerificationStatus] = useState<
    "verifying" | "success" | "error"
  >("verifying");
  const [message, setMessage] = useState("");

  useEffect(() => {
    const verifyToken = async () => {
      const token = searchParams.get("token");

      if (!token) {
        setVerificationStatus("error");
        setMessage("Le lien de vérification est manquant.");

        Swal.fire({
          icon: "error",
          title: "Lien invalide",
          text: "Ce lien de vérification est incorrect ou a expiré.",
          confirmButtonText: "Créer un compte",
        }).then(() => {
          router.push("/register");
        });
        return;
      }

      try {
        setVerificationStatus("verifying");

        Swal.fire({
          title: "Vérification de l'e-mail...",
          text: "Veuillez patienter pendant que nous vérifions votre adresse e-mail",
          imageUrl: "/loading_gif.gif",
          imageWidth: 100,
          imageHeight: 100,
          imageAlt: "Chargement...",
          showConfirmButton: false,
          allowOutsideClick: false,
          allowEscapeKey: false,
          allowEnterKey: false,
        });

        const result = await dispatch(
          verifyEmailToken({ token }) as any
        ).unwrap();

        Swal.close();
        setVerificationStatus("success");
        setMessage("E-mail vérifié avec succès !");

        Swal.fire({
          icon: "success",
          title: "Félicitations !",
          text: "Votre e-mail a été vérifié avec succès !",
          confirmButtonText: "Se connecter",
        }).then(() => {
          router.push("/login");
        });
      } catch (error: unknown) {
        Swal.close();
        setVerificationStatus("error");

        const errorMessage =
          error instanceof Error ? error.message : String(error);
        setMessage(errorMessage);

        Swal.fire({
          icon: "error",
          title: "Échec de la vérification",
          text: errorMessage,
          confirmButtonText: "Créer un compte",
        }).then(() => {
          router.push("/register");
        });
      }
    };

    verifyToken();
  }, [searchParams, dispatch, router]);

  const getStatusContent = () => {
    switch (verificationStatus) {
      case "verifying":
        return (
          <>
            <img
              src="/loading_gif.gif"
              alt="Vérification en cours..."
              className="mx-auto mb-4"
              width={100}
              height={100}
            />
            <p className="text-lg font-medium">
              Vérification de votre e-mail...
            </p>
            <p className="text-gray-600">Veuillez patienter un instant</p>
          </>
        );
      case "success":
        return (
          <>
            <div className="w-16 h-16 bg-green-500 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg
                className="w-8 h-8 text-white"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
            <p className="text-lg font-medium text-green-600">
              Adresse e-mail confirmée !
            </p>
            <p className="text-gray-600">
              Redirection vers la page de connexion...
            </p>
          </>
        );
      case "error":
        return (
          <>
            <div className="w-16 h-16 bg-red-500 rounded-full flex items-center justify-center mx-auto mb-4">
              <svg
                className="w-8 h-8 text-white"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </div>
            <p className="text-lg font-medium text-red-600">
              Échec de la vérification
            </p>
            <p className="text-gray-600">{message}</p>
          </>
        );
      default:
        return null;
    }
  };

  return (
    <div className="flex justify-center items-center min-h-screen bg-gray-50">
      <div className="bg-white p-8 rounded-lg shadow-md max-w-md w-full text-center">
        {getStatusContent()}
      </div>
    </div>
  );
};

export default EmailVerificationPage;
