import type { Component } from "solid-js";
import { A, useParams, useSearchParams } from "@solidjs/router";
import { Match, Show, Switch, createMemo, createResource } from "solid-js";
import AssignmentTeacherNextStep from "../../../../components/assignment/teacher/assignment-teacher-next-step";
import { getTeacherAssignmentReviewPageData } from "../../../../components/assignment/teacher/assignment-teacher-review.data";
import { useAuth } from "../../../../context/auth/context";
import { getAssignmentReviewHref, getDashboardHomeHref } from "../../../../lib/routes";
import styles from "../../../../components/assignment/shared/assignment-page.module.scss";

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

	const assignmentId = createMemo(() => {
		const parsed = Number(params.id);
		return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
	});

	const selectedStudentId = createMemo(() => {
		const parsed = Number(searchParams.student);
		return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
	});

	const teacherSource = createMemo(() => {
		const id = assignmentId();
		const user = auth.user();
		if (!auth.isReady() || !id || !user || user.role !== "teacher") return null;
		return { assignmentId: id, studentId: selectedStudentId() };
	});

	const [pageData] = createResource(teacherSource, ({ assignmentId, studentId }) => getTeacherAssignmentReviewPageData(assignmentId, studentId));

	return (
		<main class={styles.page}>
			<div class={styles.shell}>
				<Show
					when={pageData()}
					fallback={
						<section class={styles.emptyState}>
							<p class={styles.emptyEyebrow}>Loading next step</p>
							<h1>Pulling the latest review context for this student.</h1>
							<p>Preparing shared feedback and the next-step decision area.</p>
						</section>
					}
				>
					<Switch>
						<Match when={pageData()}>
							<AssignmentTeacherNextStep data={pageData()!} />
						</Match>
						<Match when={true}>
							<section class={styles.emptyState}>
								<p class={styles.emptyEyebrow}>Student or assignment not found</p>
								<h1>We could not open the next-step page.</h1>
								<p>Choose a student from the review queue first, or head back to the teacher dashboard.</p>
								<div class={styles.actions}>
									<A href={assignmentId() ? getAssignmentReviewHref("teacher", assignmentId()!) : getDashboardHomeHref("teacher")} class={styles.backButton}>
										Back to review
									</A>
								</div>
							</section>
						</Match>
					</Switch>
				</Show>
			</div>
		</main>
	);
};

export default TeacherAssignmentNextStepPage;
