"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import {
  buildLoginRedirect,
  isRegistrationPath,
  REGISTRATION_ENTRY_PATH,
  REGISTRATION_OTP_PATH,
  requiresRegistrationToken,
  resolveRegistrationRedirect,
  getRegistrationRoute,
} from "@/lib/auth/registrationRoutes";
import { fetchRegisterStatus } from "@/lib/auth/fetchRegisterStatus";
import { getAuthToken } from "@/lib/auth/session";
import { useTranslation } from "react-i18next";

export default function RegisterRouteGuard({
  children,
}: {
  children: React.ReactNode;
}) {
  const { t } = useTranslation("common");
  const pathname = usePathname();
  const router = useRouter();
  const [ready, setReady] = useState(false);

  useEffect(() => {
    let cancelled = false;

    async function guard() {
      if (!pathname || !isRegistrationPath(pathname)) {
        if (!cancelled) setReady(true);
        return;
      }

      const normalized = pathname.split("?")[0];

      if (normalized === REGISTRATION_ENTRY_PATH) {
        const token = getAuthToken();
        if (token) {
          const status = await fetchRegisterStatus();
          if (cancelled) return;

          if (status?.page === "home" || status?.registrationComplete) {
            router.replace("/");
            return;
          }

          if (status?.step) {
            router.replace(getRegistrationRoute(status.step));
            return;
          }
        }

        if (!cancelled) setReady(true);
        return;
      }

      if (normalized === REGISTRATION_OTP_PATH) {
        const mobile =
          typeof window !== "undefined"
            ? localStorage.getItem("mobile")
            : null;

        if (!mobile) {
          router.replace(REGISTRATION_ENTRY_PATH);
          return;
        }

        if (!cancelled) setReady(true);
        return;
      }

      if (requiresRegistrationToken(normalized)) {
        const token = getAuthToken();
        if (!token) {
          router.replace(buildLoginRedirect(normalized));
          return;
        }

        const status = await fetchRegisterStatus();
        if (cancelled) return;

        if (!status) {
          router.replace(buildLoginRedirect(normalized));
          return;
        }

        if (status.page === "home" || status.registrationComplete) {
          router.replace("/");
          return;
        }

        const redirect = resolveRegistrationRedirect(normalized, status.step);
        if (redirect) {
          router.replace(redirect);
          return;
        }
      }

      if (!cancelled) setReady(true);
    }

    setReady(false);
    void guard();

    return () => {
      cancelled = true;
    };
  }, [pathname, router]);

  if (!ready && pathname && isRegistrationPath(pathname)) {
    return (
      <div className="flex min-h-[40vh] items-center justify-center text-sm text-neutral-500">
        {t("auth.checkingRegistration")}
      </div>
    );
  }

  return children;
}
