import { useLocation, useNavigate, useSearchParams } from "@solidjs/router";
import type { Component } from "solid-js";
import { Show, createEffect, createMemo } from "solid-js";
import { useAuth } from "../../context/auth/context";
import { getDashboardMessagesHref, getDashboardMessageThreadHref } from "../../lib/routes";

const DashboardMessagesPage: Component = () => {
	const auth = useAuth();
	const location = useLocation();
	const navigate = useNavigate();
	const [searchParams] = useSearchParams();
const initialThreadId = createMemo(() => {
		const value = Number(searchParams.thread);
		return Number.isFinite(value) && value > 0 ? value : null;
	});

	createEffect(() => {
		if (!auth.isReady()) return;
		const user = auth.user();
		if (!user) return;
		const nextHref = initialThreadId()
			? getDashboardMessageThreadHref(user.role, initialThreadId()!)
			: `${getDashboardMessagesHref(user.role)}${location.search}`;
		void navigate(nextHref, { replace: true });
	});

	return (
		<Show when={auth.isReady()} fallback={<section>Loading your dashboard session…</section>}>
			<section>Redirecting to your messages…</section>
		</Show>
	);
};

export default DashboardMessagesPage;
