"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 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 {
  sendSocialMobileOtp,
  verifySocialMobileOtp,
} from "@/app/lib/socialAuth";

import { useAuth } from "@/app/context/AuthContext";
import { useLanguage } from "@/app/context/LanguageContext";
import { maskMobileNumber } from "@/app/lib/mask";

/*
|--------------------------------------------------------------------------
| Mobile Verification Content
|--------------------------------------------------------------------------
*/

function MobileVerificationContent() {
  const router = useLocaleRouter();
  const searchParams = useSearchParams();
  const { login } = useAuth();
  const { t } = useLanguage();

  const social = searchParams.get("social");

  /*
  |--------------------------------------------------------------------------
  | State
  |--------------------------------------------------------------------------
  */

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

  const [otp, setOtp] = useState("");

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

  const [loading, setLoading] = useState(false);

  const [resending, setResending] = useState(false);

  const [timer, setTimer] = useState(30);

  const [userName, setUserName] = useState("");

  /*
  |--------------------------------------------------------------------------
  | Check Social Login State
  |--------------------------------------------------------------------------
  */

  useEffect(() => {
    /*
     * Only Google social login is allowed here.
     */
    if (social !== "google") {
      router.replace("/signin");
      return;
    }

    /*
     * Temporary social login state.
     */
    const pending =
      sessionStorage.getItem(
        "social_login_pending"
      );

    const verificationToken =
      sessionStorage.getItem(
        "social_verification_token"
      );

    /*
     * Direct access protection.
     */
    if (
      pending !== "true" ||
      !verificationToken
    ) {
      router.replace("/signin");
      return;
    }

    /*
     * Get social user.
     */
    const savedUser =
      sessionStorage.getItem(
        "social_verification_user"
      );

    if (savedUser) {
      try {
        const user = JSON.parse(savedUser);

        setUserName(user?.name || "");
      } catch (error) {
        console.error(
          "Unable to parse social user:",
          error
        );
      }
    }
  }, [social, router]);

  /*
  |--------------------------------------------------------------------------
  | OTP Timer
  |--------------------------------------------------------------------------
  */

  useEffect(() => {
    if (step !== "otp") {
      return;
    }

    if (timer <= 0) {
      return;
    }

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

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

  /*
  |--------------------------------------------------------------------------
  | Send Mobile OTP
  |--------------------------------------------------------------------------
  */

  const handleSendOtp = async () => {
    /*
     * Remove any spaces.
     */
    const cleanMobile = mobile.trim();
    const cleanCountryCode = countryCode.trim();

    /*
     * Validate mobile.
     */
    if (!cleanMobile) {
      toast.error(t("auth.mobileVerification.mobileRequired", "Please enter mobile number."));
      return;
    }

    if (cleanMobile.length < 6) {
      toast.error(t("auth.mobileVerification.mobileInvalid", "Please enter a valid mobile number."));
      return;
    }

    /*
     * Validate country code.
     */
    if (!cleanCountryCode) {
      toast.error(t("auth.mobileVerification.countryCodeRequired", "Please select country code."));
      return;
    }

    try {
      setLoading(true);

      const verificationToken =
        sessionStorage.getItem(
          "social_verification_token"
        );

      if (!verificationToken) {
        router.replace("/signin");
        return;
      }

      /*
       * Send social mobile OTP.
       */
      const response =
        await sendSocialMobileOtp(
          verificationToken,
          cleanMobile,
          cleanCountryCode
        );

      console.log(
        "Social Send OTP Response:",
        response
      );

      if (!response?.success) {
        toast.error(
          response?.message ||
            t("auth.mobileVerification.sendOtpFailed", "Unable to send OTP.")
        );

        return;
      }

      /*
       * OTP screen.
       */
      setOtp("");

      setTimer(30);

      setStep("otp");

      toast.success(
        response?.message ||
          t("auth.mobileVerification.otpSentSuccessfully", "OTP sent successfully.")
      );
    } catch (error: any) {
      console.error(
        "Send social OTP error:",
        error
      );

      toast.error(
        error?.response?.data?.message ||
          error?.message ||
          t("auth.mobileVerification.sendOtpFailed", "Unable to send OTP.")
      );
    } finally {
      setLoading(false);
    }
  };

  /*
  |--------------------------------------------------------------------------
  | Verify OTP
  |--------------------------------------------------------------------------
  */

  const handleVerifyOtp = async () => {
    if (otp.length !== 6) {
      toast.error(
        t("auth.mobileVerification.enterSixDigits", "Please enter 6 digit OTP")
      );

      return;
    }

    try {
      setLoading(true);

      const verificationToken =
        sessionStorage.getItem(
          "social_verification_token"
        );

      if (!verificationToken) {
        router.replace("/signin");
        return;
      }

      /*
       * Verify social mobile OTP.
       */
      const response =
        await verifySocialMobileOtp(
          verificationToken,
          mobile.trim(),
          otp.trim(),
          countryCode.trim()
        );

      console.log(
        "Social Verify OTP Response:",
        response
      );

      if (!response?.success) {
        toast.error(
          response?.message ||
            t("auth.mobileVerification.verifyOtpFailed", "OTP verification failed.")
        );

        return;
      }

      /*
       * Backend token.
       */
      const token =
        response?.token ||
        response?.access_token;

      if (!token) {
        console.error(
          "Social verify response:",
          response
        );

        toast.error(
          t("auth.mobileVerification.tokenNotReturned", "Login token was not returned.")
        );

        return;
      }

      /*
       * Sync AuthContext state (not just localStorage) so
       * ProtectedRoute's useAuth().token is already set before
       * the router.replace below — otherwise pages guarded by
       * ProtectedRoute bounce straight back to /signin.
       */
      login(
        token,
        response?.refresh_token || "",
        (response?.user || {}) as any
      );

      /*
       * Clear temporary social data.
       */
      sessionStorage.removeItem(
        "social_verification_token"
      );

      sessionStorage.removeItem(
        "social_verification_user"
      );

      sessionStorage.removeItem(
        "social_login_pending"
      );

      sessionStorage.removeItem(
        "social_provider"
      );

      toast.success(
        t("auth.mobileVerification.loginSuccessful", "Login Successful")
      );

      /*
       * Social login completed.
       */
      router.replace(
        "/chat-with-astrologer"
      );
    } catch (error: any) {
      console.error(
        "Verify social OTP error:",
        error
      );

      toast.error(
        error?.response?.data?.message ||
          error?.message ||
          t("auth.mobileVerification.verifyOtpFailed2", "OTP Verification Failed")
      );
    } finally {
      setLoading(false);
    }
  };

  /*
  |--------------------------------------------------------------------------
  | Resend OTP
  |--------------------------------------------------------------------------
  */

  const handleResendOtp = async () => {
    if (timer > 0) {
      return;
    }

    try {
      setResending(true);

      const verificationToken =
        sessionStorage.getItem(
          "social_verification_token"
        );

      if (!verificationToken) {
        router.replace("/signin");
        return;
      }

      const response =
        await sendSocialMobileOtp(
          verificationToken,
          mobile.trim(),
          countryCode.trim()
        );

      console.log(
        "Resend Social OTP Response:",
        response
      );

      if (!response?.success) {
        toast.error(
          response?.message ||
            t("auth.mobileVerification.resendOtpFailed", "Unable to resend OTP.")
        );

        return;
      }

      /*
       * Reset timer.
       */
      setTimer(30);

      /*
       * Clear old OTP.
       */
      setOtp("");

      toast.success(
        response?.message ||
          t("auth.mobileVerification.otpResentSuccessfully", "OTP resent successfully.")
      );
    } catch (error: any) {
      console.error(
        "Resend social OTP error:",
        error
      );

      toast.error(
        error?.response?.data?.message ||
          error?.message ||
          t("auth.mobileVerification.resendOtpFailed", "Unable to resend OTP.")
      );
    } finally {
      setResending(false);
    }
  };

  /*
  |--------------------------------------------------------------------------
  | Change Mobile
  |--------------------------------------------------------------------------
  */

  const handleChangeMobile = () => {
    setStep("mobile");

    setOtp("");

    setTimer(30);
  };

  /*
  |--------------------------------------------------------------------------
  | Render
  |--------------------------------------------------------------------------
  */

  return (
    <section className="py-5 vh-100 d-flex justify-content-center align-items-center">
      <div className="container">

        <div className="row justify-content-center align-items-center">

          <div className="col-lg-5">

            {/* =====================================================
                CARD
            ====================================================== */}

            <div className="card card-bg-primary">

              <div className="card-body p-3 p-md-5">

                {/* =================================================
                    MOBILE STEP
                ================================================== */}

                {step === "mobile" && (
                  <>
                    <h2 className="text-center mb-3 text-white">
                      {t("auth.mobileVerification.heading", "Verify your Mobile number")}
                    </h2>

                    <p className="text-center mb-4 text-white">
                      {userName
                        ? `${t("auth.mobileVerification.welcome", "Welcome,")} ${userName}. `
                        : ""}
                      {t("auth.mobileVerification.enterMobileToContinue", "Please enter your mobile number to continue.")}
                    </p>

                    {/* ===========================================
                        PHONE INPUT
                    ============================================ */}

                    <div className="mb-4">

                      <label
                        className="form-label text-white"
                        htmlFor="social-mobile"
                      >
                        {t("auth.mobileVerification.mobileLabel", "Mobile Number")}
                      </label>

                      <PhoneInput
                        country="in"
                        value={
                          countryCode + mobile
                        }
                        onChange={(
                          value,
                          country
                        ) => {
                          /*
                           * react-phone-input-2 returns:
                           *
                           * value = 919876543210
                           * country.dialCode = 91
                           *
                           * Store only the mobile
                           * number separately.
                           */

                          const dialCode =
                            (
                              country as {
                                dialCode?: string;
                              }
                            )?.dialCode ||
                            "91";

                          let phone =
                            value || "";

                          if (
                            phone.startsWith(
                              dialCode
                            )
                          ) {
                            phone =
                              phone.substring(
                                dialCode.length
                              );
                          }

                          setCountryCode(
                            dialCode
                          );

                          setMobile(
                            phone.replace(
                              /\D/g,
                              ""
                            )
                          );
                        }}
                        inputProps={{
                          id: "social-mobile",
                          name: "mobile",
                          required: true,
                          autoComplete: "tel",
                        }}
                        inputClass="phone-react-input"
                         buttonClass="phone-react-btn"
                          containerClass="w-100"
                      
                      />

                    </div>

                    {/* ===========================================
                        SEND OTP
                    ============================================ */}

                    <button
                      type="button"
                      className="btn btn-primary w-100 py-3"
                      disabled={loading}
                      onClick={
                        handleSendOtp
                      }
                    >
                      {loading
                        ? t("auth.mobileVerification.sendingOtp", "Sending OTP...")
                        : t("auth.mobileVerification.sendOtp", "Send OTP")}
                    </button>

                  </>
                )}

                {/* =================================================
                    OTP STEP
                ================================================== */}

                {step === "otp" && (
                  <>
                    <h2 className="text-center mb-3 text-white">
                      {t("auth.mobileVerification.heading", "Verify your Mobile number")}
                    </h2>

                    <p className="text-center mb-4 text-white">
                      {t("auth.mobileVerification.sentCode", "We sent you a 6 digit code to verify")}
                      <br />
                      {t("auth.mobileVerification.yourMobileNumber", "your mobile number")}{" "}
                      <strong>
                        +{countryCode}{" "}
                        {maskMobileNumber(mobile)}
                      </strong>
                    </p>

                    {/* ===========================================
                        OTP INPUT
                    ============================================ */}

                    <div className="mb-4">

                      <OtpInputBox
                        value={otp}
                        onChange={setOtp}
                      />

                    </div>

                    {/* ===========================================
                        VERIFY BUTTON
                    ============================================ */}

                    <button
                      type="button"
                      className="btn btn-primary w-100 py-3"
                      disabled={loading}
                      onClick={
                        handleVerifyOtp
                      }
                    >
                      {loading
                        ? t("auth.mobileVerification.verifying", "Verifying...")
                        : t("auth.mobileVerification.verifyOtp", "Verify OTP")}
                    </button>

                    {/* ===========================================
                        RESEND OTP
                    ============================================ */}

                    <div className="text-center mt-4">

                      {timer > 0 ? (
                        <p className="mb-0 text-white">
                          {t("auth.mobileVerification.resendIn", "Resend OTP in")}

                          <strong className="ms-2">
                            {timer}s
                          </strong>
                        </p>
                      ) : (
                        <button
                          type="button"
                          className="btn btn-link text-white"
                          disabled={
                            resending
                          }
                          onClick={
                            handleResendOtp
                          }
                        >
                          {resending
                            ? t("auth.mobileVerification.resending", "Resending...")
                            : t("auth.mobileVerification.resendOtp", "Resend OTP")}
                        </button>
                      )}

                    </div>

                  </>
                )}

              </div>

            </div>

          </div>

        </div>

      </div>
    </section>
  );
}

/*
|--------------------------------------------------------------------------
| Page
|--------------------------------------------------------------------------
|
| useSearchParams() is inside MobileVerificationContent.
| Suspense prevents Next.js production prerender issues.
|
*/

export default function MobileVerificationPage() {
  const { t } = useLanguage();
  return (
    <Suspense
      fallback={
        <section className="py-5 vh-100 d-flex justify-content-center align-items-center">
          <div className="container">

            <div className="row justify-content-center">

              <div className="col-lg-5 col-md-7">

                <div className="card card-bg-primary shadow border-0 rounded-4">

                  <div className="card-body p-5 text-white text-center">

                    {t("auth.mobileVerification.loading", "Loading...")}

                  </div>

                </div>

              </div>

            </div>

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