"use client";

import { Suspense, useEffect, useState } from "react";
import { useLocaleRouter } from "@/app/lib/useLocaleRouter";
import Link from "@/app/components/LocaleLink";
import Image from "next/image";
import toast from "react-hot-toast";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import OtpInputBox from "@/app/components/OtpInputBox";
import {
  astrologerLogin,
  verifyAstrologerLoginOtp,
  resendAstrologerOtp,
  updateAstrologerDeviceToken,
  friendlyErrorMessage,
} from "@/app/lib/astrologer";
import { requestFcmToken } from "@/app/lib/pushNotifications";
import { maskMobileNumber } from "@/app/lib/mask";
import { useLanguage } from "@/app/context/LanguageContext";

function AstrologerSignInContent() {
  const router = useLocaleRouter();
  const { t } = useLanguage();

  const [step, setStep] = useState<"mobile" | "otp">("mobile");

  const [mobile, setMobile] = useState("");
  const [countryCode, setCountryCode] = useState("91");
  const [otp, setOtp] = useState("");

  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);
  const [timer, setTimer] = useState(30);

  useEffect(() => {
    if (step !== "otp" || timer === 0) return;

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

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

  const sendOtp = async () => {
    if (mobile.replace(countryCode, "").length < 10) {
      toast.error(t("astrologerAuth.signin.toastInvalidMobile", "Enter a valid mobile number"));
      return;
    }

    try {
      setLoading(true);

      const localMobile = mobile.startsWith(countryCode)
        ? mobile.slice(countryCode.length)
        : mobile;

      const response = await astrologerLogin(
        localMobile,
        `+${countryCode}`
      );

      if (response.success) {
        toast.success(t("astrologerAuth.signin.toastOtpSent", "OTP sent"));
        setStep("otp");
        setTimer(30);
      } else if (
        (response.message || "").toLowerCase().includes("not found")
      ) {
        // Step A of the auth flow: no astrologer account for this
        // mobile -> send them to Register instead of a dead-end error.
        toast(
          t(
            "astrologerAuth.signin.toastNotFoundRedirect",
            "No astrologer account found for this number — let's register you."
          ),
          { icon: "ℹ️" }
        );

        router.push(
          `/astrologer/register?mobile=${encodeURIComponent(
            localMobile
          )}`
        );
      } else {
        toast.error(friendlyErrorMessage(response.message, t("astrologerAuth.signin.toastSendOtpFailedFallback", "Unable to send OTP")));
      }
    } catch (error: any) {
      const message: string =
        error.response?.data?.message ?? t("astrologerAuth.signin.toastSendOtpErrorFallback", "Unable to send OTP.");

      if (message.toLowerCase().includes("not found")) {
        // Step A of the auth flow: no astrologer account for this
        // mobile -> send them to Register instead of a dead-end error.
        toast(
          t(
            "astrologerAuth.signin.toastNotFoundRedirect",
            "No astrologer account found for this number — let's register you."
          ),
          { icon: "ℹ️" }
        );

        const localMobile = mobile.startsWith(countryCode)
          ? mobile.slice(countryCode.length)
          : mobile;

        router.push(
          `/astrologer/register?mobile=${encodeURIComponent(localMobile)}`
        );
      } else {
        toast.error(message);
      }
    } finally {
      setLoading(false);
    }
  };

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

    try {
      setLoading(true);

      const localMobile = mobile.startsWith(countryCode)
        ? mobile.slice(countryCode.length)
        : mobile;

      const response = await verifyAstrologerLoginOtp(
        localMobile,
        otp
      );

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

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

      if (!token) {
        toast.error(t("astrologerAuth.signin.toastNoTokenReturned", "Login token was not returned."));
        return;
      }

      localStorage.setItem("astrologerToken", token);

      // Fire-and-forget: must never block the redirect below on a
      // notification-permission prompt or a slow/failed FCM call.
      requestFcmToken()
        .then((fcmToken) => fcmToken && updateAstrologerDeviceToken(fcmToken, token))
        .catch(() => {});

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

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

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

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

      toast.success(
        t("astrologerAuth.signin.toastLoginSuccess", "Login successful")
      );

      // Verified astrologer -> go directly to dashboard
      // Unverified astrologer -> continue profile progress flow
      if (user?.is_verified === true) {
        router.push("/astrologer/dashboard");
      } else {
        router.push("/astrologer/profile/progress");
      }
    } catch (error: any) {
      toast.error(
        error.response?.data?.message ?? t("astrologerAuth.signin.toastVerifyOtpErrorFallback", "Unable to verify OTP.")
      );
    } finally {
      setLoading(false);
    }
  };

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

      const localMobile = mobile.startsWith(countryCode)
        ? mobile.slice(countryCode.length)
        : mobile;

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

      if (response.success) {
        toast.success(t("astrologerAuth.signin.toastOtpResent", "OTP resent"));
        setTimer(30);
        setOtp("");
      } else {
        toast.error(friendlyErrorMessage(response.message, t("astrologerAuth.signin.toastResendOtpFailedFallback", "Unable to resend OTP")));
      }
    } catch (error: any) {
      toast.error(
        error.response?.data?.message ?? t("astrologerAuth.signin.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="card card-bg-primary border-0 shadow rounded-4">
              <div className="card-body p-4 p-md-5 text-white">
                {step === "mobile" ? (
                  <>
                    <h2 className="text-center mb-2">
                      <span className="text-warning">{t("astrologerAuth.signin.headingHighlight", "Astrologer")}</span>{" "}
                      {t("astrologerAuth.signin.heading", "sign in")}
                    </h2>

                    <p className="text-center terms-text-color mb-4">
                      {t(
                        "astrologerAuth.signin.subtitle",
                        "Enter the mobile number registered with your astrologer account. We'll send a one-time code."
                      )}
                    </p>

                    <div className="mb-4">
                      <PhoneInput
                        country="in"
                        value={mobile}
                        onChange={(value, country: any) => {
                          setMobile(value);
                          setCountryCode(country.dialCode);
                        }}
                        inputClass="phone-react-input"
                        buttonClass="phone-react-btn"
                      />
                    </div>

                    <button
                      className="btn btn-primary w-100 py-3"
                      onClick={sendOtp}
                      disabled={loading}
                    >
                      {loading ? t("astrologerAuth.signin.sendingButton", "Sending...") : t("astrologerAuth.signin.sendOtpButton", "Send OTP")}
                    </button>

                    <p className="text-center terms-text-color mt-4 mb-0">
                      <small>
                        {t(
                          "astrologerAuth.signin.termsNotice",
                          "By continuing you agree to the astrologer terms and the consultation payout policy."
                        )}
                      </small>
                    </p>

                    <p className="text-center mt-4 mb-0 terms-text-color">
                      {t("astrologerAuth.signin.newAstrologerPrompt", "New astrologer?")}{" "}
                      <Link
                        href="/astrologer/register"
                        className="fw-semibold"
                      >
                        {t("astrologerAuth.signin.registerLink", "Register")}
                      </Link>
                    </p>
                  </>
                ) : (
                  <div className="text-center">
                    <h4 className="mb-2">{t("astrologerAuth.signin.otpHeading", "Verify your number")}</h4>

                    <p className="terms-text-color">
                      {t("astrologerAuth.signin.otpSubtitle", "We sent you a 6 digit code to verify your mobile number")}
                      <br />
                      <strong>+{countryCode} {maskMobileNumber(mobile.replace(countryCode, ""))}</strong>
                    </p>

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

                    <p className="terms-text-color mb-4">
                      {t("astrologerAuth.signin.resendPrompt", "Didn't receive code?")}{" "}
                      {timer > 0 ? (
                        <span>{t("astrologerAuth.signin.resendCountdownPrefix", "Resend OTP (")}{timer}{t("astrologerAuth.signin.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.signin.resendingButton", "Resending...") : t("astrologerAuth.signin.resendButton", "Resend OTP")}
                        </button>
                      )}
                    </p>

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

                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
    </>
  );
}

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