// Path: Frontend/src/components/assignment/teacher/assignment-teacher-review.sections.tsx

import type { Component, JSX } from "solid-js";
import { A } from "@solidjs/router";
import { createSignal, For, Show } from "solid-js";
import { assignmentUiCopy } from "~/content/ui-copy";
import type { TeacherAssignmentReviewPageData, TeacherReviewDraftFields, TeacherReviewNotice, TeacherReviewQuestion } from "./assignment-teacher-review.types";
import { getDashboardAssignmentsHref } from "../../../lib/routes";
import styles from "./assignment-teacher-review.module.scss";

const toneClass = (tone: string) => {
	switch (tone) {
		case "review":
			return styles.review;
		case "progress":
			return styles.progress;
		case "success":
			return styles.success;
		default:
			return styles.muted;
	}
};

type AssignmentFeedbackSectionProps = {
	data: TeacherAssignmentReviewPageData;
	teacherFeedbackDraft: string;
	hasPendingAssignmentFeedback: boolean;
	busy: boolean;
	notice: TeacherReviewNotice;
	draftActionLabel: string;
	actions?: JSX.Element;
	onTeacherFeedbackInput: (value: string) => void;
};

export const AssignmentFeedbackSection: Component<AssignmentFeedbackSectionProps> = (props) => (
	<section class={styles.assignmentFeedbackCard}>
		<div class={styles.sectionHeader}>
			<h3>{assignmentUiCopy.teacherReview.feedback.title}</h3>
			<p>Keep AI feedback and teacher feedback in one place for the whole assignment.</p>
		</div>

		<div class={styles.supportBlock}>
			<p>{assignmentUiCopy.teacherReview.feedback.aiFeedback}</p>
			<span>{props.data.assignmentAiFeedback || assignmentUiCopy.teacherReview.feedback.noAiFeedback}</span>
		</div>

		<div class={styles.feedbackBlock}>
			<label for="assignment-feedback">{assignmentUiCopy.teacherReview.feedback.teacherFeedback}</label>
			<textarea
				id="assignment-feedback"
				class={styles.feedbackInput}
				value={props.teacherFeedbackDraft}
				onInput={(event) => props.onTeacherFeedbackInput(event.currentTarget.value)}
				disabled={props.busy}
				placeholder={assignmentUiCopy.teacherReview.feedback.teacherFeedbackPlaceholder}
			/>
		</div>

		<Show when={props.notice?.scope === "assignment"}>
			<div class={`${styles.notice} ${props.notice?.tone === "error" ? styles.noticeError : styles.noticeSuccess}`}>{props.notice?.text}</div>
		</Show>

		<div class={styles.draftHint}>
			<Show when={props.hasPendingAssignmentFeedback} fallback={<span>{assignmentUiCopy.teacherReview.feedback.cleanDraft}</span>}>
				<span>{assignmentUiCopy.teacherReview.feedback.dirtyDraftPrefix} {props.draftActionLabel}.</span>
			</Show>
		</div>

		<Show when={props.actions}>{(actions) => <div class={styles.actionRow}>{actions()}</div>}</Show>
	</section>
);

type QuestionCardProps = {
	cardId?: string;
	question: TeacherReviewQuestion;
	notice: TeacherReviewNotice;
	hasPendingDraft: boolean;
	savingAll: boolean;
	onResetDraft: (question: TeacherReviewQuestion) => void;
	onNeedsAttention: (question: TeacherReviewQuestion) => void;
	onReviewFieldChange: (question: TeacherReviewQuestion, patch: Partial<TeacherReviewDraftFields>) => void;
};

export const TeacherReviewQuestionCard: Component<QuestionCardProps> = (props) => (
	<article id={props.cardId} class={styles.questionCard}>
		<div class={styles.questionTop}>
			<div>
				<p class={styles.order}>{assignmentUiCopy.teacherReview.question.questionPrefix} {props.question.order}</p>
				<h3>{props.question.prompt}</h3>
			</div>
			<span class={`${styles.statusPill} ${toneClass(props.question.statusTone)}`}>{props.question.statusLabel}</span>
		</div>

		<div class={styles.metaRow}>
			<span>{props.question.submittedLabel}</span>
			<span>{props.question.reviewedLabel}</span>
		</div>

		<div class={styles.responseBlock}>
			<p>{assignmentUiCopy.teacherReview.question.studentAnswer}</p>
			<strong>{props.question.answerText}</strong>
		</div>

		<Show when={props.question.workingSteps || props.question.solveModeLabel}>
			<div class={styles.supportBlock}>
				<p>{assignmentUiCopy.teacherReview.question.studentSteps}</p>
				<Show when={props.question.solveModeLabel}>
					<span>{props.question.solveModeLabel}</span>
				</Show>
				<Show when={props.question.workingSteps} fallback={<span>{assignmentUiCopy.teacherReview.question.noSteps}</span>}>
					<pre>{props.question.workingSteps}</pre>
				</Show>
			</div>
		</Show>

		<div class={styles.supportBlock}>
			<p>{assignmentUiCopy.teacherReview.question.correctAnswer}</p>
			<Show when={props.question.correctAnswer} fallback={<span>{assignmentUiCopy.teacherReview.question.noCorrectAnswer}</span>}>
				<strong>{props.question.correctAnswer}</strong>
			</Show>
		</div>

		<Show when={props.question.answerId} fallback={<div class={styles.reviewDraftEmpty}>{assignmentUiCopy.teacherReview.question.structuredReviewLocked}</div>}>
			<div class={styles.reviewEditorCard}>
				<div class={styles.reviewEditorTop}>
					<h4>{assignmentUiCopy.teacherReview.question.structuredReview}</h4>
					<label class={styles.reviewCheckbox}>
						<input
							type="checkbox"
							checked={props.question.reviewNeedsAttention}
							disabled={props.savingAll}
							onChange={(event) =>
								props.onReviewFieldChange(props.question, {
									reviewNeedsAttention: event.currentTarget.checked,
								})
							}
						/>
						<span>{assignmentUiCopy.teacherReview.question.needsAttention}</span>
					</label>
				</div>

				<small>{assignmentUiCopy.teacherReview.question.weightingNote}</small>

				<div class={styles.reviewField}>
					<label for={`issue-reason-${props.question.id}`}>{assignmentUiCopy.teacherReview.question.issueReason}</label>
					<textarea
						id={`issue-reason-${props.question.id}`}
						class={styles.feedbackInput}
						value={props.question.reviewIssueReason}
						disabled={props.savingAll}
						placeholder={assignmentUiCopy.teacherReview.question.issueReasonPlaceholder}
						onInput={(event) =>
							props.onReviewFieldChange(props.question, {
								reviewIssueReason: event.currentTarget.value,
							})
						}
					/>
				</div>

				<div class={styles.reviewScoreGrid}>
					<div class={styles.reviewField}>
						<label for={`understanding-score-${props.question.id}`}>{assignmentUiCopy.teacherReview.question.understandingScore}</label>
						<input
							id={`understanding-score-${props.question.id}`}
							type="number"
							class={styles.compactInput}
							min="0"
							max="1"
							step="0.05"
							value={props.question.reviewUnderstandingScore ?? ""}
							disabled={props.savingAll}
							onInput={(event) =>
								props.onReviewFieldChange(props.question, {
									reviewUnderstandingScore: event.currentTarget.value === "" ? null : Number(event.currentTarget.value),
								})
							}
						/>
					</div>

					<div class={styles.reviewField}>
						<label for={`confidence-score-${props.question.id}`}>{assignmentUiCopy.teacherReview.question.confidence}</label>
						<input
							id={`confidence-score-${props.question.id}`}
							type="number"
							class={styles.compactInput}
							min="0"
							max="1"
							step="0.05"
							value={props.question.reviewConfidence ?? ""}
							disabled={props.savingAll}
							onInput={(event) =>
								props.onReviewFieldChange(props.question, {
									reviewConfidence: event.currentTarget.value === "" ? null : Number(event.currentTarget.value),
								})
							}
						/>
					</div>
				</div>

				<div class={styles.reviewField}>
					<label>{assignmentUiCopy.teacherReview.question.questionTags}</label>
					<Show
						when={props.question.questionTags.length > 0}
						fallback={<small>{assignmentUiCopy.teacherReview.question.noSavedTags}</small>}
					>
						<div class={styles.tagList}>
							<For each={props.question.questionTags}>{(tag) => <span class={styles.tagPill}>{tag}</span>}</For>
						</div>
						<small>{assignmentUiCopy.teacherReview.question.inheritedTags}</small>
					</Show>
				</div>
			</div>
		</Show>

		<Show when={props.notice?.scope === "question" && props.notice?.questionId === props.question.id}>
			<div class={`${styles.notice} ${props.notice?.tone === "error" ? styles.noticeError : styles.noticeSuccess}`}>{props.notice?.text}</div>
		</Show>

		<div class={styles.actionRow}>
			<Show when={props.hasPendingDraft}>
				<button type="button" class={styles.secondaryAction} disabled={!props.question.answerId || props.savingAll} onClick={() => props.onResetDraft(props.question)}>
					{assignmentUiCopy.teacherReview.question.resetDraft}
				</button>
			</Show>
			<button type="button" class={styles.primaryAction} disabled={!props.question.answerId || props.savingAll} onClick={() => props.onNeedsAttention(props.question)}>
				{props.hasPendingDraft ? assignmentUiCopy.teacherReview.question.needsAttentionInDraft : assignmentUiCopy.teacherReview.question.needsAttention}
			</button>
		</div>
	</article>
);

type TeacherReviewSaveProgressCardProps = {
	canMoveToNextStep: boolean;
	pendingChangeCount: number;
	savingAll: boolean;
	closeState: TeacherAssignmentReviewPageData["closeSummary"]["state"];
	notice: TeacherReviewNotice;
	onSave: () => void;
};

export const TeacherReviewSaveProgressCard: Component<TeacherReviewSaveProgressCardProps> = (props) => (
	<section class={styles.saveAllCard}>
		<div class={styles.sectionHeader}>
			<h3>{assignmentUiCopy.teacherReview.saveProgress.title}</h3>
			<p>
				<Show
					when={props.canMoveToNextStep}
					fallback={
						props.closeState === "closed"
							? assignmentUiCopy.teacherReview.saveProgress.closedFallback
							: assignmentUiCopy.teacherReview.saveProgress.lockedFallback
					}
				>
					{props.pendingChangeCount} question{props.pendingChangeCount === 1 ? " is" : "s are"} flagged for attention. Everything else will be marked reviewed when you continue.
				</Show>
			</p>
		</div>

		<Show when={props.notice?.scope === "global"}>
			<div class={`${styles.notice} ${props.notice?.tone === "error" ? styles.noticeError : styles.noticeSuccess}`}>{props.notice?.text}</div>
		</Show>

		<div class={styles.actionRow}>
			<button type="button" class={styles.primaryAction} disabled={props.savingAll || !props.canMoveToNextStep || props.closeState === "closed"} onClick={props.onSave}>
				{props.savingAll ? assignmentUiCopy.teacherReview.saveProgress.saving : assignmentUiCopy.teacherReview.saveProgress.saveAndNextStep}
			</button>
		</div>
	</section>
);

type TeacherReviewSidebarProps = {
	data: TeacherAssignmentReviewPageData;
	hasQueue: boolean;
	closingAssignment: boolean;
	closeNotice: TeacherReviewNotice;
	onSelectStudent: (studentId: number) => void;
	onCloseAssignment: () => void;
};

export const TeacherReviewSidebar: Component<TeacherReviewSidebarProps> = (props) => (
	(() => {
		const [isQueueExpanded, setIsQueueExpanded] = createSignal(false);

		return (
			<aside class={styles.sideColumn}>
				<section class={`${styles.sideCard} ${styles.queueCard} ${styles.mobileStickyNav}`}>
					<div class={styles.mobileStickyNavHeader}>
						<div>
							<p class={styles.sideEyebrow}>{assignmentUiCopy.teacherReview.sidebar.queueEyebrow}</p>
							<h2>{assignmentUiCopy.teacherReview.sidebar.studentsToReview}</h2>
							<p>Select a student to switch the question review panel.</p>
						</div>
						<button
							type="button"
							class={styles.mobileStickyNavToggle}
							aria-expanded={isQueueExpanded()}
							onClick={() => setIsQueueExpanded((value) => !value)}
						>
							{isQueueExpanded() ? "Hide queue" : "Open queue"}
						</button>
					</div>
					<div class={styles.sideActions}>
						<A href={getDashboardAssignmentsHref("teacher")} class={styles.secondaryAction}>
							{assignmentUiCopy.teacherReview.sidebar.backToDashboard}
						</A>
					</div>
					<div classList={{ [styles.mobileStickyNavContent]: true, [styles.mobileStickyNavContentExpanded]: isQueueExpanded() }}>
						<div class={styles.queueScroller}>
							<div class={styles.queueList}>
								<Show when={props.hasQueue} fallback={<div class={styles.queueEmpty}>{assignmentUiCopy.teacherReview.sidebar.queueEmpty}</div>}>
									<For each={props.data.reviewQueue}>
										{(item) => (
											<button
												type="button"
												class={`${styles.queueButton} ${props.data.selectedStudentId === item.studentId ? styles.queueButtonActive : ""}`.trim()}
												onClick={() => {
													props.onSelectStudent(item.studentId);
													setIsQueueExpanded(false);
												}}
											>
												<div>
													<strong>{item.studentName}</strong>
													<p>{item.progressLabel}</p>
												</div>
												<div class={styles.queueMeta}>
													<span class={`${styles.statusPill} ${toneClass(item.statusTone)}`}>{item.statusLabel}</span>
													<small>{item.timestampLabel}</small>
												</div>
											</button>
										)}
									</For>
								</Show>
							</div>
						</div>
					</div>
				</section>

				<section class={styles.sideCard}>
					<p class={styles.sideEyebrow}>{assignmentUiCopy.teacherReview.sidebar.statusEyebrow}</p>
					<h2>{assignmentUiCopy.teacherReview.sidebar.closeAssignment}</h2>
					<p>{props.data.closeSummary.summary}</p>
					<div class={styles.closeAssignmentStatusRow}>
						<span
							class={`${styles.statusPill} ${
								props.data.closeSummary.state === "closed"
									? styles.muted
									: props.data.closeSummary.state === "ready"
										? styles.success
										: styles.review
							}`}
						>
							{props.data.closeSummary.state === "closed"
								? assignmentUiCopy.teacherReview.sidebar.closed
								: props.data.closeSummary.state === "ready"
									? assignmentUiCopy.teacherReview.sidebar.readyToClose
									: assignmentUiCopy.teacherReview.sidebar.blocked}
						</span>
					</div>
					<Show when={props.data.closeSummary.blockers.length > 0}>
						<ul class={styles.closeBlockerList}>
							<For each={props.data.closeSummary.blockers}>{(blocker) => <li>{blocker}</li>}</For>
						</ul>
					</Show>
					<Show when={props.closeNotice?.scope === "assignment"}>
						<div class={`${styles.notice} ${props.closeNotice?.tone === "error" ? styles.noticeError : styles.noticeSuccess}`}>{props.closeNotice?.text}</div>
					</Show>
					<div class={styles.sideActions}>
						<button type="button" class={styles.primaryAction} disabled={!props.data.closeSummary.canClose || props.closingAssignment} onClick={props.onCloseAssignment}>
							{props.closingAssignment ? assignmentUiCopy.teacherReview.sidebar.closing : props.data.closeSummary.state === "closed" ? assignmentUiCopy.teacherReview.sidebar.assignmentClosed : assignmentUiCopy.teacherReview.sidebar.closeAssignment}
						</button>
					</div>
				</section>

				<section class={styles.sideCard}>
					<p class={styles.sideEyebrow}>{assignmentUiCopy.teacherReview.sidebar.overviewEyebrow}</p>
					<h2>{props.data.selectedStudentName ?? assignmentUiCopy.teacherReview.sidebar.reviewSummary}</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>
				</section>
			</aside>
		);
	})()
);
