"use client";

import { useSearchParams, useRouter } from "next/navigation";
import { useEffect, useRef } from "react";
import { useModal } from "../../lib/modal-system/ModalContext";
import { ModalType } from "../../lib/modal-system/ModalRegistery";
import { useAppDispatch } from "../../hooks/useAppRedux";
import { errorToast } from "../../utils/toast";
import { clearUser } from "../../store/slices/user";

export default function HomeClient() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const { openModal, modal } = useModal();
  const hasOpenedRef = useRef(false);
  const dispatch = useAppDispatch();

  useEffect(() => {
    const modalParam = searchParams.get("modal");
    const token = searchParams.get("token");
    const reason = searchParams.get("reason");
    const logout = searchParams.get("logout");

    let shouldCleanUrl = false;

    if (modalParam && modal.type === null && !hasOpenedRef.current) {
      hasOpenedRef.current = true;
      openModal(modalParam as ModalType, { token: token ?? undefined } as any);
      shouldCleanUrl = true;
    }

    if (reason === "session_expired") {
      errorToast("You were logged out. Please sign in again.");
      shouldCleanUrl = true;
    }

    if (logout) {
      dispatch(clearUser());
      shouldCleanUrl = true;
    }

    if (shouldCleanUrl) {
      router.replace("/", { scroll: false });
      router.refresh();
    }
  }, [searchParams, modal.type, openModal, dispatch, router]);

  return null;
}
