import type { Component } from "solid-js";
import { A, useNavigate } from "@solidjs/router";
import { createEffect, createMemo, createSignal, For, Show } from "solid-js";
import type { TeacherAssignmentPassStatus, TeacherAssignmentReviewPageData, TeacherNextStepOutcome } from "./assignment-teacher-review.data";
import { updateAssignmentTeacherFeedback } from "./assignment-teacher-review.data";
import { AssignmentFeedbackSection, type TeacherReviewNotice } from "./assignment-teacher-review.sections";
import { getAssignmentReviewHref, getTeacherAssignmentRedoPlanHref } from "../../../lib/routes";
import styles from "./assignment-teacher-review.module.scss";

type Props = {
	data: TeacherAssignmentReviewPageData;
};

type NextStepDraft = {
	teacherFeedback?: string;
	decision?: TeacherNextStepOutcome;
	passStatusOverride?: TeacherAssignmentPassStatus | null;
};

const PASS_STATUS_OVERRIDE_OPTIONS: Array<{ value: TeacherAssignmentPassStatus | null; label: string; help: string }> = [
	{ value: null, label: "Automatic", help: "Use the calculated status from the fixed pass rule." },
	{ value: "pass", label: "Pass", help: "Override the calculated result and mark this review as pass." },
	{ value: "no_pass", label: "No pass", help: "Override the calculated result and mark this review as no pass." },
];

const nextStepStorageKey = (assignmentId: number, studentId: number) => `teacher-next-step-draft:${assignmentId}:${studentId}`;

const readNextStepDraft = (assignmentId: number, studentId: number): NextStepDraft => {
	if (typeof window === "undefined") return {};

	try {
		const raw = window.localStorage.getItem(nextStepStorageKey(assignmentId, studentId));
		if (!raw) return {};
		const parsed = JSON.parse(raw);
		return parsed && typeof parsed === "object" ? (parsed as NextStepDraft) : {};
	} catch {
		return {};
	}
};

const writeNextStepDraft = (assignmentId: number, studentId: number, draft: NextStepDraft) => {
	if (typeof window === "undefined") return;
	const key = nextStepStorageKey(assignmentId, studentId);
	if (!draft.teacherFeedback && !draft.decision && draft.passStatusOverride == null) {
		window.localStorage.removeItem(key);
		return;
	}
	window.localStorage.setItem(key, JSON.stringify(draft));
};

const OUTCOME_OPTIONS: Array<{ value: TeacherNextStepOutcome; title: string; description: string }> = [
	{ value: "redo", title: "Redo assignment", description: "Ask the student to revisit the assignment and try again with the latest review in mind." },
	{ value: "accept", title: "Accept and continue", description: "Mark this review as ready to move on and continue the student into the next piece of work." },
	{ value: "support", title: "Needs support", description: "Flag that the student needs extra coaching, a follow-up message, or a guided reteach step." },
];

const AssignmentTeacherNextStep: Component<Props> = (props) => {
	const navigate = useNavigate();
	const [teacherFeedbackDraft, setTeacherFeedbackDraft] = createSignal("");
	const [decisionDraft, setDecisionDraft] = createSignal<TeacherNextStepOutcome | null>(null);
	const [passStatusOverrideDraft, setPassStatusOverrideDraft] = createSignal<TeacherAssignmentPassStatus | null>(null);
	const [savingFeedback, setSavingFeedback] = createSignal(false);
	const [notice, setNotice] = createSignal<TeacherReviewNotice>(null);

	const selectedStudentId = createMemo(() => props.data.selectedStudentId);
	const canChooseNextStep = createMemo(() => {
		return props.data.selectedStudentSubmittedQuestions > 0 || props.data.selectedStudentReviewedQuestions > 0;
	});
	const hasPendingAssignmentFeedback = createMemo(() => teacherFeedbackDraft() !== props.data.assignmentTeacherFeedback);
	const hasPendingDecision = createMemo(() => decisionDraft() !== props.data.nextStepOutcome);
	const hasPendingPassStatusOverride = createMemo(() => passStatusOverrideDraft() !== props.data.passStatusOverride);
	const overallScorePercent = createMemo(() => {
		if (props.data.overallScore == null) return null;
		return Math.round(props.data.overallScore * 10);
	});

	createEffect(() => {
		const studentId = selectedStudentId();
		if (!studentId) return;
		const draft = readNextStepDraft(props.data.assignmentId, studentId);
		setTeacherFeedbackDraft(draft.teacherFeedback ?? props.data.assignmentTeacherFeedback);
		setDecisionDraft(draft.decision ?? props.data.nextStepOutcome);
		setPassStatusOverrideDraft(draft.passStatusOverride ?? props.data.passStatusOverride);
		setNotice(null);
	});

	createEffect(() => {
		const studentId = selectedStudentId();
		if (!studentId) return;
		writeNextStepDraft(props.data.assignmentId, studentId, {
			teacherFeedback: hasPendingAssignmentFeedback() ? teacherFeedbackDraft() : undefined,
			decision: hasPendingDecision() ? decisionDraft() ?? undefined : undefined,
			passStatusOverride: hasPendingPassStatusOverride() ? passStatusOverrideDraft() : undefined,
		});
	});

	const saveFeedback = async () => {
		const studentId = selectedStudentId();
		if (!studentId) return;
		if (!canChooseNextStep()) {
			setNotice({
				scope: "assignment",
				tone: "error",
				text: "Next step stays locked until the student has submitted work for review.",
			});
			return;
		}

		setSavingFeedback(true);
		setNotice(null);
		try {
			if (hasPendingAssignmentFeedback() || hasPendingPassStatusOverride() || hasPendingDecision()) {
				await updateAssignmentTeacherFeedback(props.data.assignmentId, studentId, {
					teacherFeedback: teacherFeedbackDraft().trim(),
					passStatusOverride: passStatusOverrideDraft(),
					nextStepOutcome: decisionDraft(),
				});
			}

			writeNextStepDraft(props.data.assignmentId, studentId, {});
			if (decisionDraft() === "redo") {
				navigate(getTeacherAssignmentRedoPlanHref(props.data.assignmentId, studentId));
				return;
			}
			navigate(getAssignmentReviewHref("teacher", props.data.assignmentId));
		} catch (error) {
			setNotice({
				scope: "assignment",
				tone: "error",
				text: error instanceof Error ? error.message : "Could not save teacher feedback right now.",
			});
		} finally {
			setSavingFeedback(false);
		}
	};

	return (
		<div class={styles.contentGrid}>
			<div class={styles.mainColumn}>
				<section class={styles.section}>
					<div class={styles.sectionHeader}>
						<h2>Choose the next step</h2>
						<p>
							<Show when={props.data.selectedStudentName} fallback="Choose what should happen after this review.">
								{props.data.selectedStudentName} has been reviewed. Choose what should happen next, then save your feedback at the bottom before returning to the review page.
							</Show>
						</p>
					</div>

					<Show when={props.data.selectedStudentId !== null} fallback={<div class={styles.emptyState}>Pick a student from the review queue first so you can set the right next step.</div>}>
						<Show
							when={canChooseNextStep()}
							fallback={<div class={styles.emptyState}>This student has not submitted work yet, so next step is not available.</div>}
						>
						<section class={styles.nextStepCard}>
							<div class={styles.sectionHeader}>
								<h3>Recommended outcome</h3>
								<p>Pick the next teaching move for {props.data.selectedStudentName ?? "this student"}. The selected outcome will be saved with this student's review.</p>
							</div>

						<div class={styles.optionGrid}>
								<For each={OUTCOME_OPTIONS}>
									{(option) => (
										<button
											type="button"
											class={`${styles.optionCard} ${decisionDraft() === option.value ? styles.optionCardActive : ""}`.trim()}
											onClick={() => setDecisionDraft(option.value)}
										>
											<strong>{option.title}</strong>
											<span>{option.description}</span>
										</button>
									)}
								</For>
							</div>

				<div class={styles.draftHint}>
					<Show when={decisionDraft()} fallback={<span>No next-step outcome has been picked yet.</span>}>
						<span>Selected outcome: {OUTCOME_OPTIONS.find((option) => option.value === decisionDraft())?.title}. Save feedback to persist it for this student.</span>
					</Show>
				</div>

					<div class={styles.reviewScoreGrid}>
						<div class={`${styles.reviewField} ${styles.scoreHighlight}`.trim()}>
							<label>Overall score</label>
							<div class={styles.scoreHighlightValue}>
								<Show when={overallScorePercent() != null} fallback={<span>Pending review</span>}>
									<strong>{overallScorePercent()}%</strong>
								</Show>
							</div>
							<small>
								<Show when={props.data.overallScore != null} fallback="The score will appear after the review has been completed.">
									Blended correctness and understanding score.
								</Show>
							</small>
						</div>

						<div class={styles.reviewField}>
							<label>Pass status</label>
							<input
								type="text"
								class={styles.compactInput}
								value={props.data.passStatus === "no_pass" ? "No pass" : props.data.passStatus === "pass" ? "Pass" : "Pending"}
								readOnly
								disabled
							/>
							<small>
								<Show when={props.data.passStatusOverride} fallback="Currently using the automatic result.">
									Teacher override is active.
								</Show>
							</small>
						</div>

						<div class={styles.reviewField}>
							<label>Teacher override</label>
							<select
								class={styles.compactInput}
								value={passStatusOverrideDraft() ?? ""}
								onInput={(event) => {
									const value = event.currentTarget.value.trim();
									setPassStatusOverrideDraft(value === "pass" || value === "no_pass" || value === "pending" ? value : null);
								}}
							>
								<For each={PASS_STATUS_OVERRIDE_OPTIONS}>
									{(option) => (
										<option value={option.value ?? ""}>{option.label}</option>
									)}
								</For>
							</select>
							<small>{PASS_STATUS_OVERRIDE_OPTIONS.find((option) => option.value === passStatusOverrideDraft())?.help ?? PASS_STATUS_OVERRIDE_OPTIONS[0]!.help}</small>
						</div>
					</div>
					</section>

						<AssignmentFeedbackSection
							data={props.data}
							teacherFeedbackDraft={teacherFeedbackDraft()}
							hasPendingAssignmentFeedback={hasPendingAssignmentFeedback()}
							busy={savingFeedback()}
							notice={notice()}
							draftActionLabel="Save and return to review"
							onTeacherFeedbackInput={setTeacherFeedbackDraft}
							actions={
								<button type="button" class={styles.primaryAction} disabled={savingFeedback()} onClick={saveFeedback}>
									{savingFeedback()
										? decisionDraft() === "redo"
											? "Saving and opening redo plan..."
											: "Saving and returning..."
										: decisionDraft() === "redo"
											? "Save feedback and open redo plan"
											: "Save feedback and return to review"}
								</button>
							}
						/>
						</Show>
					</Show>
				</section>
			</div>

			<aside class={styles.sideColumn}>
				<section class={styles.sideCard}>
					<p class={styles.sideEyebrow}>Student</p>
					<h2>{props.data.selectedStudentName ?? "Review summary"}</h2>
					<p>{props.data.selectedStudentEmail ?? props.data.coachCard.description}</p>
					<Show when={props.data.selectedStudentProgress}>
						<div class={styles.progressNote}>{props.data.selectedStudentProgress}</div>
					</Show>
					<ul class={styles.noteList}>
						<For each={props.data.coachCard.items}>{(item) => <li>{item}</li>}</For>
					</ul>
					<div class={styles.actionRow}>
						<A href={getAssignmentReviewHref("teacher", props.data.assignmentId)} class={styles.secondaryAction}>
							Back to review
						</A>
					</div>
				</section>
			</aside>
		</div>
	);
};

export default AssignmentTeacherNextStep;
