import type { Component } from "solid-js";
import { Show, createMemo, createResource } from "solid-js";
import { useSearchParams } from "@solidjs/router";
import DashboardMessagesPage from "../../../components/dashboard/messages/dashboard-messages.page";
import DashboardShell from "../../../components/dashboard/shared/dashboard-shell";
import { getDashboardHomeData } from "../../../components/dashboard/student/dashboard-home.data";
import { useAuth } from "~/context/auth/context";

const StudentDashboardMessagesPage: Component = () => {
	const auth = useAuth();
	const [searchParams] = useSearchParams();
	const studentId = createMemo(() => (auth.isReady() && auth.user()?.role === "student" ? auth.user()!.id : null));
	const [shellData] = createResource(studentId, getDashboardHomeData);
	const initialThreadId = createMemo(() => {
		const value = Number(searchParams.thread);
		return Number.isFinite(value) && value > 0 ? value : null;
	});

	return (
		<DashboardShell sidebarData={shellData()?.shell} topbarData={shellData()?.shell}>
			<Show when={auth.isReady()} fallback={<section>Loading your dashboard session…</section>}>
				<Show when={studentId()} keyed fallback={<section>Sign in to access your internal inbox.</section>}>
					{(userId) => <DashboardMessagesPage currentUserId={userId} initialThreadId={initialThreadId()} />}
				</Show>
			</Show>
		</DashboardShell>
	);
};

export default StudentDashboardMessagesPage;
