import type { Component } from "solid-js";
import { A, useParams } from "@solidjs/router";
import { Show, createMemo, createResource } from "solid-js";
import AssignmentHeader from "../../../../components/assignment/shared/assignment-header";
import AssignmentOverview from "../../../../components/assignment/shared/assignment-overview";
import AssignmentQuestionList from "../../../../components/assignment/shared/assignment-question-list";
import AssignmentTabs from "../../../../components/assignment/shared/assignment-tabs";
import { getAssignmentReviewPageData } from "../../../../components/assignment/student/assignment-review.data";
import { useAuth } from "../../../../context/auth/context";
import { getDashboardHomeHref } from "../../../../lib/routes";
import styles from "../../../../components/assignment/shared/assignment-page.module.scss";

const StudentAssignmentPage: Component = () => {
	const params = useParams();
	const auth = useAuth();
	const assignmentId = createMemo(() => {
		const parsed = Number(params.id);
		return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
	});
	const studentSource = createMemo(() => {
		const id = assignmentId();
		const user = auth.user();
		if (!auth.isReady() || !id || !user || user.role !== "student") return null;
		return { assignmentId: id, studentId: user.id };
	});
	const [assignmentData] = createResource(studentSource, ({ assignmentId, studentId }) => getAssignmentReviewPageData(assignmentId, studentId));

	return (
		<main class={styles.page}>
			<div class={styles.shell}>
				<Show
					when={!assignmentData.loading}
					fallback={
						<section class={styles.emptyState}>
							<p class={styles.emptyEyebrow}>Loading assignment</p>
							<h1>Pulling the latest review data from the backend.</h1>
							<p>This page now loads from the live API instead of the local mock file.</p>
						</section>
					}
				>
					<Show
						when={assignmentData()}
						fallback={
							<section class={styles.emptyState}>
								<p class={styles.emptyEyebrow}>Assignment not found</p>
								<h1>We could not find that assignment.</h1>
								<p>Try a seeded assignment like 3007, or jump back to the dashboard.</p>
								<A href={getDashboardHomeHref("student")} class={styles.backButton}>
									Back to dashboard
								</A>
							</section>
						}
					>
						{(data) => (
							<>
								<AssignmentHeader data={data()} backHref={getDashboardHomeHref("student")} />
								<AssignmentTabs role="student" />

								<div class={styles.contentGrid}>
									<div class={styles.mainColumn}>
										<AssignmentQuestionList data={data()} />
									</div>

									<aside class={styles.sideColumn}>
										<AssignmentOverview data={data()} />
									</aside>
								</div>
							</>
						)}
					</Show>
				</Show>
			</div>
		</main>
	);
};

export default StudentAssignmentPage;
