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 { getTeacherDashboardHomeData } from "../../../components/dashboard/teacher/dashboard-teacher-home.data";
import { useAuth } from "~/context/auth/context";

const TeacherDashboardMessagesPage: Component = () => {
	const auth = useAuth();
	const [searchParams] = useSearchParams();
	const teacherId = createMemo(() => (auth.isReady() && auth.user()?.role === "teacher" ? auth.user()!.id : null));
	const [shellData] = createResource(teacherId, getTeacherDashboardHomeData);
	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={teacherId()} keyed fallback={<section>Sign in to access your internal inbox.</section>}>
					{(userId) => <DashboardMessagesPage currentUserId={userId} initialThreadId={initialThreadId()} />}
				</Show>
			</Show>
		</DashboardShell>
	);
};

export default TeacherDashboardMessagesPage;
