import type { Component } from "solid-js";
import { A, useParams, useSearchParams } from "@solidjs/router";
import { Match, Show, Switch, createMemo, createResource } from "solid-js";
import AssignmentTeacherRedoPlan from "../../../../components/assignment/teacher/assignment-teacher-redo-plan";
import { getTeacherAssignmentRedoPlanData } 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 TeacherAssignmentRedoPlanPage: 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 studentId = selectedStudentId();
		const user = auth.user();
		if (!auth.isReady() || !id || !studentId || !user || user.role !== "teacher") return null;
		return { assignmentId: id, studentId };
	});

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

	return (
		<main class={styles.page}>
			<div class={styles.shell}>
				<Show
					when={pageData()}
					fallback={
						<section class={styles.emptyState}>
							<p class={styles.emptyEyebrow}>Loading redo plan</p>
							<h1>Pulling the latest weakness summary and redo blueprint.</h1>
							<p>Preparing the planning output for this student.</p>
						</section>
					}
				>
					<Switch>
						<Match when={pageData()}>
							<AssignmentTeacherRedoPlan data={pageData()!} />
						</Match>
						<Match when={true}>
							<section class={styles.emptyState}>
								<p class={styles.emptyEyebrow}>Redo plan not found</p>
								<h1>We could not open that redo plan.</h1>
								<p>Save the next-step page with Redo selected first, or return to the teacher review flow.</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 TeacherAssignmentRedoPlanPage;
