"use client";

import { Suspense, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";

import { useLocaleRouter } from "@/app/lib/useLocaleRouter";
import Link from "@/app/components/LocaleLink";
import Image from "next/image";
import toast from "react-hot-toast";

import OtpInputBox from "@/app/components/OtpInputBox";
import {
  verifyAstrologerEmailOtp,
  resendAstrologerOtp,
  updateAstrologerDeviceToken,
  friendlyErrorMessage,
} from "@/app/lib/astrologer";
import { requestFcmToken } from "@/app/lib/pushNotifications";
import { maskEmail } from "@/app/lib/mask";
import { useLanguage } from "@/app/context/LanguageContext";

function VerifyEmailContent() {
  const router = useLocaleRouter();
  const params = useSearchParams();
  const { t } = useLanguage();

  const mobile = params.get("mobile") || "";

  const [email, setEmail] = useState(params.get("email") || "");
  const [otp, setOtp] = useState("");
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);
  const [timer, setTimer] = useState(30);

  useEffect(() => {
    if (timer === 0) return;

    const interval = setInterval(() => {
      setTimer((prev) => prev - 1);
    }, 1000);

    return () => clearInterval(interval);
  }, [timer]);

  const verify = async () => {
    if (!email) {
      toast.error(t("astrologerAuth.verifyEmail.toastEnterEmail", "Enter your email address"));
      return;
    }

    if (otp.length !== 6) {
      toast.error(t("astrologerAuth.verifyEmail.toastInvalidOtpCode", "Enter the 6 digit code"));
      return;
    }

    try {
      setLoading(true);

      const response = await verifyAstrologerEmailOtp(email, otp);

      if (!response.success) {
        toast.error(friendlyErrorMessage(response.message, t("astrologerAuth.verifyEmail.toastInvalidOtpFallback", "Invalid OTP")));
        return;
      }

      toast.success(t("astrologerAuth.verifyEmail.toastEmailVerified", "Email verified"));

      const token =
        response.data?.token ?? response.token ?? null;

      if (token) {
        localStorage.setItem("astrologerToken", token);

        // Fire-and-forget: must never block the redirect below.
        requestFcmToken()
          .then((fcmToken) => fcmToken && updateAstrologerDeviceToken(fcmToken, token))
          .catch(() => {});

        const refreshToken =
          response.data?.refresh_token ??
          response.refresh_token ??
          null;

        if (refreshToken) {
          localStorage.setItem(
            "astrologerRefreshToken",
            refreshToken
          );
        }

        const user = response.data?.astrologer ?? response.data;

        if (user) {
          localStorage.setItem(
            "astrologerUser",
            JSON.stringify(user)
          );
        }

        router.push("/astrologer/profile/progress");
      } else {
        router.push(
          `/astrologer/signin?mobile=${encodeURIComponent(mobile)}`
        );
      }
    } catch (error: any) {
      toast.error(
        error.response?.data?.message ?? t("astrologerAuth.verifyEmail.toastVerifyOtpErrorFallback", "Unable to verify OTP.")
      );
    } finally {
      setLoading(false);
    }
  };

  const resend = async () => {
    try {
      setResending(true);

      const response = await resendAstrologerOtp(mobile, "email");

      if (response.success) {
        toast.success(t("astrologerAuth.verifyEmail.toastOtpResent", "OTP resent"));
        setTimer(30);
        setOtp("");
      } else {
        toast.error(friendlyErrorMessage(response.message, t("astrologerAuth.verifyEmail.toastResendOtpFailedFallback", "Unable to resend OTP")));
      }
    } catch (error: any) {
      toast.error(
        error.response?.data?.message ?? t("astrologerAuth.verifyEmail.toastResendOtpErrorFallback", "Unable to resend OTP.")
      );
    } finally {
      setResending(false);
    }
  };

  return (
    <section className="py-5 d-flex align-items-center min-vh-100">
      <div className="container">
        <div className="row justify-content-center">
          <div className="col-lg-5">
            <div className="text-center mb-4">
              <Link href="/astrologer">
                <Image
                  src="/images/logo-astro.svg"
                  alt="AstroEye"
                  width={140}
                  height={119}
                  priority
                />
              </Link>
            </div>

            <div className="card card-bg-primary border-0 shadow rounded-4">
              <div className="card-body p-3 p-md-5 text-white text-center">
                <h4 className="mb-2">{t("astrologerAuth.verifyEmail.heading", "Verify your email")}</h4>

                {email ? (
                  <p className="terms-text-color">
                    {t("astrologerAuth.verifyEmail.subtitleWithEmail", "We sent a 6 digit verification code to")}
                    <br />
                    <strong>{maskEmail(email)}</strong>
                  </p>
                ) : (
                  <>
                    <p className="terms-text-color">
                      {t("astrologerAuth.verifyEmail.subtitleNoEmail", "Enter the email address on your astrologer account to verify it.")}
                    </p>

                    <input
                      type="email"
                      placeholder={t("astrologerAuth.verifyEmail.emailPlaceholder", "Email address")}
                      className="form-control form-control-lg text-center mb-3"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    />
                  </>
                )}

                <div className="d-flex justify-content-center my-4">
                  <OtpInputBox value={otp} onChange={setOtp} />
                </div>

                <p className="terms-text-color mb-4">
                  {t("astrologerAuth.verifyEmail.resendPrompt", "Didn't receive code?")}{" "}
                  {timer > 0 ? (
                    <span>{t("astrologerAuth.verifyEmail.resendCountdownPrefix", "Resend OTP (")}{timer}{t("astrologerAuth.verifyEmail.resendCountdownSuffix", "s)")}</span>
                  ) : (
                    <button
                      type="button"
                      className="btn btn-link p-0 text-danger fw-semibold text-decoration-none"
                      onClick={resend}
                      disabled={resending}
                    >
                      {resending ? t("astrologerAuth.verifyEmail.resendingButton", "Resending...") : t("astrologerAuth.verifyEmail.resendButton", "Resend OTP")}
                    </button>
                  )}
                </p>

                <button
                  className="btn btn-primary w-100 py-3"
                  onClick={verify}
                  disabled={loading}
                >
                  {loading ? t("astrologerAuth.verifyEmail.verifyingButton", "Verifying...") : t("astrologerAuth.verifyEmail.submitButton", "Submit")}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

export default function AstrologerVerifyEmailPage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <VerifyEmailContent />
    </Suspense>
  );
}
