"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";
import { useVerifyEmailData } from "@/app/hooks/useData";

const EmailVerificationPage = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useDispatch();
  const { data: translations } = useVerifyEmailData();
  const t = translations || {};
  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(t.Status?.No_Token_Message || "No verification token found");

        Swal.fire({
          icon: "error",
          title: t.SweetAlert?.Invalid_Token_Title || "Invalid Token",
          text:
            t.SweetAlert?.Invalid_Token_Text ||
            "No verification token found in the URL",
          confirmButtonText:
            t.SweetAlert?.Invalid_Token_Button || "Go to Register",
        }).then(() => {
          router.push("/register");
        });
        return;
      }

      try {
        setVerificationStatus("verifying");

        Swal.fire({
          title: t.SweetAlert?.Verifying_Title || "Verifying Email...",
          text:
            t.SweetAlert?.Verifying_Text ||
            "Please wait while we verify your email address",
          imageUrl: "/loading_gif.gif",
          imageWidth: 100,
          imageHeight: 100,
          imageAlt: t.SweetAlert?.Verifying_Alt || "Loading...",
          showConfirmButton: false,
          allowOutsideClick: false,
          allowEscapeKey: false,
          allowEnterKey: false,
        });

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

        Swal.close();
        setVerificationStatus("success");
        setMessage(
          result.message ||
            t.Common?.Email_Verified_Success ||
            "Email verified successfully!"
        );

        Swal.fire({
          icon: "success",
          title: t.SweetAlert?.Success_Title || "Email Verified!",
          text:
            result.message ||
            t.SweetAlert?.Success_Text ||
            "Your email has been verified successfully!",
          confirmButtonText: t.SweetAlert?.Success_Button || "Go to Login",
        }).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: t.SweetAlert?.Error_Title || "Verification Failed",
          text: errorMessage,
          confirmButtonText: t.SweetAlert?.Error_Button || "Go to Register",
        }).then(() => {
          router.push("/register");
        });
      }
    };

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

  const getStatusContent = () => {
    switch (verificationStatus) {
      case "verifying":
        return (
          <>
            <img
              src="/loading_gif.gif"
              alt={t.Status?.Verifying_Alt || "Verifying..."}
              className="mx-auto mb-4"
              width={100}
              height={100}
            />
            <p className="text-lg font-medium">
              {t.Status?.Verifying_Title || "Verifying your email..."}
            </p>
            <p className="text-gray-600">
              {t.Status?.Verifying_Subtitle || "Please wait a moment"}
            </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">
              {t.Status?.Success_Title || "Email Verified Successfully!"}
            </p>
            <p className="text-gray-600">
              {t.Status?.Success_Subtitle || "Redirecting to login page..."}
            </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">
              {t.Status?.Error_Title || "Verification Failed"}
            </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;
