import type { Component } from "solid-js";
import { useNavigate } from "@solidjs/router";
import { createSignal } from "solid-js";
import { useAuth } from "~/context/auth/context";
import { getAssignmentReviewHref } from "../../../lib/routes";
import { createRedoAssignmentForStudent } from "./assignment-teacher-redo-plan.helpers";
import { RedoPlanMainColumn, RedoPlanSidebar } from "./assignment-teacher-redo-plan.sections";
import type { AssignmentTeacherRedoPlanProps } from "./assignment-teacher-redo-plan.types";
import styles from "./assignment-teacher-review.module.scss";

const AssignmentTeacherRedoPlan: Component<AssignmentTeacherRedoPlanProps> = (props) => {
	const auth = useAuth();
	const navigate = useNavigate();
	const [isCreatingRedoAssignment, setIsCreatingRedoAssignment] = createSignal(false);
	const [generationError, setGenerationError] = createSignal<string | null>(null);
	const [generationSuccess, setGenerationSuccess] = createSignal<string | null>(null);

	const handleGenerateRedoQuestions = async () => {
		if (!props.data.plan?.questionSet.length) return;
		const teacherId = auth.user()?.role === "teacher" ? auth.user()!.id : null;
		if (!teacherId) {
			setGenerationError("Your teacher session is still loading.");
			return;
		}

		setIsCreatingRedoAssignment(true);
		setGenerationError(null);
		setGenerationSuccess(null);

		try {
			const result = await createRedoAssignmentForStudent({
				data: props.data,
				teacherId,
			});

			setGenerationSuccess(result.successMessage);
			void navigate(getAssignmentReviewHref("teacher", result.assignmentId));
		} catch (error) {
			setGenerationError(error instanceof Error ? error.message : "Unable to create the redo assignment right now.");
		} finally {
			setIsCreatingRedoAssignment(false);
		}
	};

	return (
		<div class={styles.contentGrid}>
			<RedoPlanMainColumn data={props.data} />
			<RedoPlanSidebar
				data={props.data}
				isCreatingRedoAssignment={isCreatingRedoAssignment()}
				generationError={generationError()}
				generationSuccess={generationSuccess()}
				onGenerateRedoQuestions={() => void handleGenerateRedoQuestions()}
			/>
		</div>
	);
};

export default AssignmentTeacherRedoPlan;
