import type { Component } from "solid-js";
import { Show, createMemo, createResource } from "solid-js";
import { useParams, useSearchParams } from "@solidjs/router";
import DashboardShell from "../../../../components/dashboard/shared/dashboard-shell";
import DashboardTeacherClassroomDetail from "../../../../components/dashboard/teacher/dashboard-teacher-classroom-detail";
import { getTeacherClassroomDetailData } from "../../../../components/dashboard/teacher/dashboard-teacher-classroom-detail.data";
import { useAuth } from "~/context/auth/context";

const TeacherDashboardClassroomDetailPage: Component = () => {
	const auth = useAuth();
	const params = useParams();
	const [searchParams] = useSearchParams();

	const teacherId = createMemo(() => (auth.isReady() && auth.user()?.role === "teacher" ? auth.user()!.id : null));
	const classroomId = createMemo(() => {
		const value = Number(params.id);
		return Number.isFinite(value) ? value : null;
	});
	const selectedStudentId = createMemo(() => {
		const raw = searchParams.student;
		if (!raw) return null;
		const value = Number(raw);
		return Number.isFinite(value) ? value : null;
	});

	const [detailData] = createResource(
		() => {
			const teacher = teacherId();
			const classroom = classroomId();
			if (teacher == null || classroom == null) return null;
			return { teacherId: teacher, classroomId: classroom, selectedStudentId: selectedStudentId() };
		},
		(args) => getTeacherClassroomDetailData(args.teacherId, args.classroomId, args.selectedStudentId),
	);

	const shellData = createMemo(() => detailData()?.shell);

	return (
		<DashboardShell sidebarData={shellData()} topbarData={shellData()}>
			<Show when={auth.isReady()} fallback={<section>Loading your dashboard session…</section>}>
				<Show when={auth.user()?.role === "teacher"} fallback={<section>This classroom view is for teacher accounts.</section>}>
					<Show when={classroomId() != null} fallback={<section>We could not determine which classroom to open.</section>}>
						<Show when={!detailData.error} fallback={<section>We could not load this classroom right now.</section>}>
							<Show when={detailData() !== undefined} fallback={<section>Loading this classroom…</section>}>
								<Show when={detailData()} keyed fallback={<section>We could not find that classroom for this teacher.</section>}>
									{(data) => <DashboardTeacherClassroomDetail data={data} />}
								</Show>
							</Show>
						</Show>
					</Show>
				</Show>
			</Show>
		</DashboardShell>
	);
};

export default TeacherDashboardClassroomDetailPage;
