"use client";

import { useCallback, useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";

import "./astrologer-theme.css";
import Spinner from "@/app/components/Spinner";
import AstrologerTopbar from "@/app/components/astrologer/AstrologerTopbar";
import { getProfileProgress, isBlockedMessage, logoutBlockedAstrologer } from "@/app/lib/astrologer";
import { getAstrologerAuthToken } from "@/app/lib/astrologer-token";
import { ProfileProgress, getNextStepRoute } from "@/app/lib/astrologerSteps";

/*
|--------------------------------------------------------------------------
| Approval gate for the astrologer dashboard family
|--------------------------------------------------------------------------
| The dashboard, orders, wallet, consultations, notifications, profile hub and
| profile edit pages are only for APPROVED astrologers. Registration, sign-in,
| the wizard steps, progress, thank-you and under-review pages stay open.
|
| The gate asks the backend on every navigation into a protected page
| (GET /astrologer/profile/progress) instead of trusting anything cached, and
| renders nothing from the page until the answer is "approved" — so a pending,
| rejected or half-registered astrologer never sees (or triggers API calls
| from) a dashboard page, even by typing the URL.
*/

function isProtectedPath(pathname: string): boolean {
  return (
    pathname === "/astrologer/profile" ||
    pathname.startsWith("/astrologer/profile/edit") ||
    pathname.startsWith("/astrologer/profile-hub") ||
    pathname.startsWith("/astrologer/dashboard") ||
    pathname.startsWith("/astrologer/requests") ||
    pathname.startsWith("/astrologer/wallet") ||
    pathname.startsWith("/astrologer/consultation") || // also /consultations
    pathname.startsWith("/astrologer/notifications")
  );
}

// Pages an astrologer can open without being signed in. Everything else under
// /astrologer needs a session (astrologerToken) and bounces to the sign-in page
// otherwise.
function isPublicPath(pathname: string): boolean {
  return (
    pathname === "/astrologer" ||
    pathname === "/astrologer/signin" ||
    pathname === "/astrologer/register" ||
    pathname === "/astrologer/verify-mobile" ||
    pathname === "/astrologer/verify-email"
  );
}

function isApproved(progress: ProfileProgress): boolean {
  const adminStatus = String(progress.admin_status ?? "").trim().toUpperCase();

  if (adminStatus) return adminStatus === "APPROVED";

  // No explicit status: fall back to the documented next_screen contract.
  return (
    progress.is_profile_completed !== false &&
    progress.next_screen !== "create_profile" &&
    progress.next_screen !== "profile_under_review"
  );
}

// Where a not-yet-approved astrologer belongs.
function holdingRoute(progress: ProfileProgress): string {
  if (!progress.is_profile_completed) return getNextStepRoute(progress);

  const adminStatus = String(progress.admin_status ?? "").trim().toUpperCase();

  // Rejected by the admin: the progress page shows the rejection notice and a
  // Logout button (no re-submit), never the "under review" screen.
  if (adminStatus.includes("REJECT")) return "/astrologer/profile/progress";

  // Same rule as the progress page: only PENDING / under-review counts as
  // submitted; anything else (draft, rejected, ...) goes back to the checklist
  // where "Submit Profile" is reachable.
  const submitted =
    progress.next_screen === "profile_under_review" || adminStatus === "PENDING";

  return submitted ? "/astrologer/profile/review" : "/astrologer/profile/progress";
}

export default function AstrologerLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const router = useRouter();

  // The pathname the last successful check was for.
  const [approvedFor, setApprovedFor] = useState<string | null>(null);
  const [failed, setFailed] = useState(false);
  const [attempt, setAttempt] = useState(0);

  const protectedPath = isProtectedPath(pathname);
  const publicPath = isPublicPath(pathname);

  // Signed-in-only pages that are not approval-gated (registration wizard,
  // progress, under review, thank you): just require a session.
  const [sessionFor, setSessionFor] = useState<string | null>(null);

  const check = useCallback(async () => {
    const token = getAstrologerAuthToken();

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

    try {
      const response = await getProfileProgress(token);

      const progress: ProfileProgress = response?.data ?? response;

      if (!progress || typeof progress !== "object" || response?.success === false) {
        throw new Error("progress unavailable");
      }

      if (isApproved(progress)) {
        setFailed(false);
        setApprovedFor(pathname);
        return;
      }

      router.replace(holdingRoute(progress));
    } catch (error: any) {
      if (error?.response?.status === 401) {
        router.replace("/astrologer/signin");
        return;
      }

      // Fail closed: never show dashboard pages when approval can't be confirmed.
      setFailed(true);
    }
  }, [pathname, router]);

  useEffect(() => {
    if (publicPath || protectedPath) return;

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

    setSessionFor(pathname);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname]);

  useEffect(() => {
    if (!protectedPath) return;

    setFailed(false);
    setApprovedFor(null);
    check();
    // `attempt` re-runs the check from the "Try again" button.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname, attempt]);

  // While an approved dashboard page is open, re-check the account every minute:
  // an astrologer the admin has just blocked is logged out and told so, instead
  // of staying signed in until the next page load.
  const approvedHere = protectedPath && approvedFor === pathname;

  useEffect(() => {
    if (!approvedHere) return;

    const interval = setInterval(async () => {
      const token = getAstrologerAuthToken();

      if (!token) return;

      try {
        await getProfileProgress(token);
      } catch (error: any) {
        const status = error?.response?.status;

        if ((status === 401 || status === 403) && isBlockedMessage(error?.response?.data?.message)) {
          logoutBlockedAstrologer();
        }
      }
    }, 60000);

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

  if (protectedPath && approvedFor === pathname) {
    // Approved dashboard pages share one fixed header (greeting, language,
    // notifications, profile photo); each page renders its own breadcrumb.
    return (
      <>
        <AstrologerTopbar />
        <div className="astro-with-topbar">{children}</div>
      </>
    );
  }

  if (publicPath || (!protectedPath && sessionFor === pathname)) {
    return <>{children}</>;
  }

  if (failed) {
    return (
      <section className="py-5 d-flex align-items-center justify-content-center min-vh-100">
        <div className="text-center text-white">
          <p className="mb-3">We couldn&apos;t verify your account right now.</p>
          <button type="button" className="btn btn-primary" onClick={() => setAttempt((n) => n + 1)}>
            Try again
          </button>
        </div>
      </section>
    );
  }

  return (
    <section className="py-5 d-flex align-items-center justify-content-center min-vh-100">
      <Spinner />
    </section>
  );
}
