"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";

import type { PublishCapability, PublishIntent } from "@/lib/publishPermissions";
import { usePublishFormIntent } from "./usePublishFormIntent";
import { type RouteUserType, routeAccess } from "@/components/shared/routeAccess";
import { useAuthStore } from "@/store/authStore";
import { useSessionReady } from "@/store/useSessionReady";
import { useQuery } from "@tanstack/react-query";
import { getOrganizerProfile } from "@/features/profile/services/profileApi";
import Loader from "@/components/ui/Loader";
import Button from "@/components/ui/Button";
import { useTranslation } from "react-i18next";

interface ProtectedRouteProps {
  children: React.ReactNode;
  userType?: RouteUserType | RouteUserType[];
  /**
   * For the publish forms: the page opens only for a user who may publish at
   * least one of these (`lib/publishPermissions.ts`). Checked on top of
   * `userType`, and it already covers approval and bans — a pending, rejected
   * or banned organization used to reach every form by URL.
   */
  publish?: PublishCapability | PublishCapability[];
  publishIntent?: PublishIntent;
  publishNavStateKey?: "volunteer_form_details" | "learn_serve_form_details" | "event_form_details";
}

/**
 * Client-side guard: withholds the screen and redirects a reader who should
 * not be here.
 *
 * **This is a UX boundary, not a security one.** It runs after hydration, so
 * the route's HTML is already on its way — only the backend token check keeps
 * data out of an anonymous reader's hands. What it ships is the layout shell:
 * because this component returns `null` during the server render, the guarded
 * page body is not in the prerendered HTML at all.
 *
 * The decision itself lives in `routeAccess`, which is where it is tested. It
 * used to be written out twice in this file — once here and once in the effect
 * — and two copies of an access rule is one too many.
 */
export default function ProtectedRoute({
  children,
  userType,
  publish,
  publishIntent = "create",
  publishNavStateKey,
}: ProtectedRouteProps) {
  const user = useAuthStore((s) => s.user);
  const sessionReady = useSessionReady();
  const router = useRouter();
  const { t } = useTranslation();
  // Peek once; the form remains the sole consumer of the navigation payload.
  // Holding the intent keeps consuming that payload from changing an edit into a create.
  const intent = usePublishFormIntent(publishIntent, publishNavStateKey);
  const needsPublisherType = Boolean(publish && user?.user_type === "organization" && user.is_verified === true && user.is_banned !== true && (user.is_publishing_paused !== true || intent === "edit") && !user.organizer_type_display?.value_en);
  const publisherProfile = useQuery({ queryKey: ["organizer-profile"], queryFn: getOrganizerProfile, enabled: sessionReady && needsPublisherType, retry: false });
  const display = publisherProfile.data?.data?.organizer_type_display;
  const waitingForType = needsPublisherType && !display?.value_en;
  const resolvedUser = user && display?.value_en ? { ...user, organizer_type_display: { ...display, id: display.id ?? undefined } } : user;
  const { allow, redirectTo } = routeAccess({ user: resolvedUser, userType, publish, publishIntent: intent });

  useEffect(() => {
    /*
     * Nothing until the session is known to React.
     *
     * `user` is legitimately `null` for one render on the client: the server
     * cannot know the session (the token is in `localStorage`, not a cookie),
     * so the server snapshot is signed-out and the hydration render uses it —
     * which is what makes the two agree. Redirecting on that render would
     * send a signed-in reader to `/login` on every reload.
     *
     * This is a one-render wait, not a fetch: the rehydrate is synchronous and
     * already complete before React runs. See `useSessionReady`.
     */
    if (!sessionReady || waitingForType) return;
    if (redirectTo) router.replace(redirectTo);
    /* `replace`, not `push`: Back should return to wherever the reader came
       from, not to a screen that will redirect them again. */
  }, [sessionReady, waitingForType, redirectTo, router]);

  /* Withheld in the same render that schedules the redirect, so the screen
     never flashes while the navigation is in flight — and withheld during the
     unknown render too, which is what the server rendered for this subtree. */
  if (sessionReady && waitingForType) {
    if (publisherProfile.isLoading) return <Loader />;
    return <div role="alert" className="space-y-4 p-8 text-center"><p>{t("COMMON.PUBLISHER_TYPE_LOAD_ERROR")}</p><Button onClick={() => { void publisherProfile.refetch(); }}>{t("COMMON.RETRY")}</Button></div>;
  }
  if (!allow) return null;

  return <>{children}</>;
}
