import { A } from "@solidjs/router";
import type { Component, JSX } from "solid-js";
import { For, Show } from "solid-js";
import { dashboardUiCopy } from "~/content/ui-copy";
import { getDashboardAssignmentsHref, getDashboardHomeHref } from "../../../lib/routes";
import styles from "./dashboard-teacher-assignments.module.scss";
import { FIXED_PASS_THRESHOLD_LABEL, GENERATION_DIFFICULTY_OPTIONS, GENERATION_TOPIC_OPTIONS } from "./dashboard-teacher-assignment-create.constants";
import type { AssignmentSetupForm, QuestionGenerationForm } from "./dashboard-teacher-assignment-create.types";
import type { TeacherAssignmentSetupData } from "./dashboard-teacher-assignments.data";

type InputHandler = (event: Event) => void;

export const AssignmentCreateHero: Component = () => (
	<article class={styles.heroCard}>
		<div class={styles.heroCopy}>
			<p class={styles.eyebrow}>{dashboardUiCopy.teacherAssignmentCreate.hero.eyebrow}</p>
			<h1>{dashboardUiCopy.teacherAssignmentCreate.hero.title}</h1>
			<p>Create live homework from here without crowding the main Assignments hub.</p>
		</div>

		<div class={styles.formActions}>
			<A href={getDashboardAssignmentsHref("teacher")} class={styles.primaryAction}>
				{dashboardUiCopy.teacherAssignmentCreate.hero.backToAssignments}
			</A>
			<A href={getDashboardHomeHref("teacher")} class={styles.secondaryAction}>
				{dashboardUiCopy.teacherAssignmentCreate.hero.teachingOverview}
			</A>
		</div>
	</article>
);

type AssignmentDetailsSectionProps = {
	form: AssignmentSetupForm;
	classrooms: TeacherAssignmentSetupData["classrooms"];
	selectedQuestionCount: number;
	onInput: (field: "classroomId" | "title" | "instructions" | "dueAt") => InputHandler;
};

export const AssignmentDetailsSection: Component<AssignmentDetailsSectionProps> = (props) => (
	<>
		<div class={styles.setupHeader}>
			<div>
				<p class={styles.eyebrow}>{dashboardUiCopy.teacherAssignmentCreate.details.eyebrow}</p>
				<h2>{dashboardUiCopy.teacherAssignmentCreate.details.title}</h2>
				<p>Pick a class, then either attach shared bank questions or publish a mixed personalized homework set for every student.</p>
			</div>
			<div class={styles.setupBadge}>{props.selectedQuestionCount} {dashboardUiCopy.teacherAssignmentCreate.details.selectedSuffix}</div>
		</div>

		<div class={styles.fieldGrid}>
			<label class={styles.fieldLabel}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.details.classroom}</span>
				<select class={styles.selectInput} value={props.form.classroomId} onInput={props.onInput("classroomId")}>
					<option value="">{dashboardUiCopy.teacherAssignmentCreate.details.chooseClassroom}</option>
					<For each={props.classrooms}>{(classroom) => <option value={classroom.id}>{classroom.name}</option>}</For>
				</select>
			</label>

			<div class={styles.fieldLabel}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.details.passThreshold}</span>
				<input class={styles.textInput} value={FIXED_PASS_THRESHOLD_LABEL} disabled />
			</div>

			<label class={styles.fieldLabel}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.details.dueDate}</span>
				<input class={styles.textInput} type="datetime-local" value={props.form.dueAt} onInput={props.onInput("dueAt")} />
			</label>

			<label class={`${styles.fieldLabel} ${styles.fieldLabelFull}`}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.details.assignmentTitle}</span>
				<input class={styles.textInput} value={props.form.title} onInput={props.onInput("title")} placeholder={dashboardUiCopy.teacherAssignmentCreate.details.assignmentTitlePlaceholder} />
			</label>

			<label class={`${styles.fieldLabel} ${styles.fieldLabelFull}`}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.details.teacherNotes}</span>
				<textarea
					class={styles.textArea}
					rows={4}
					value={props.form.instructions}
					onInput={props.onInput("instructions")}
					placeholder={dashboardUiCopy.teacherAssignmentCreate.details.teacherNotesPlaceholder}
				/>
			</label>
		</div>
	</>
);

type PersonalizedGenerationSectionProps = {
	form: AssignmentSetupForm;
	mixedGenerationEnabled: boolean;
	mixedGenerationQuestionCount: number;
	mixedGenerationRatioLabel: string;
	onInput: (field: "primaryTopic" | "primaryDifficulty" | "totalQuestions" | "personalizedRatio" | "seed" | "personalizedDifficulty" | "subject") => InputHandler;
	onToggle: InputHandler;
};

export const PersonalizedGenerationSection: Component<PersonalizedGenerationSectionProps> = (props) => (
	<div class={styles.generatorPanel}>
		<div class={styles.questionPickerHeader}>
			<div>
				<h3>{dashboardUiCopy.teacherAssignmentCreate.personalized.title}</h3>
				<p>Optionally generate a mixed question set for each student at publish time using one shared homework blueprint.</p>
			</div>
			<small>{props.mixedGenerationEnabled ? dashboardUiCopy.teacherAssignmentCreate.personalized.enabled : dashboardUiCopy.teacherAssignmentCreate.personalized.disabled}</small>
		</div>

		<label class={styles.toggleRow}>
			<input type="checkbox" checked={props.form.useMixedGeneration} onChange={props.onToggle} />
			<div>
				<strong>{dashboardUiCopy.teacherAssignmentCreate.personalized.toggleTitle}</strong>
				<span>Uses the backend 70/30 mixed planner during assignment publish instead of relying on one shared question list.</span>
			</div>
		</label>

		<Show when={props.mixedGenerationEnabled}>
			<div class={styles.fieldGrid}>
				<label class={styles.fieldLabel}>
					<span>{dashboardUiCopy.teacherAssignmentCreate.personalized.primaryTopic}</span>
					<select class={styles.selectInput} value={props.form.primaryTopic} onInput={props.onInput("primaryTopic")}>
						<For each={GENERATION_TOPIC_OPTIONS}>{(option) => <option value={option.value}>{option.label}</option>}</For>
					</select>
				</label>

				<label class={styles.fieldLabel}>
					<span>{dashboardUiCopy.teacherAssignmentCreate.personalized.primaryDifficulty}</span>
					<select class={styles.selectInput} value={props.form.primaryDifficulty} onInput={props.onInput("primaryDifficulty")}>
						<For each={GENERATION_DIFFICULTY_OPTIONS}>{(option) => <option value={option.value}>{option.label}</option>}</For>
					</select>
				</label>

				<label class={styles.fieldLabel}>
					<span>{dashboardUiCopy.teacherAssignmentCreate.personalized.totalQuestions}</span>
					<input class={styles.textInput} type="number" min="1" value={props.form.totalQuestions} onInput={props.onInput("totalQuestions")} />
				</label>

				<label class={styles.fieldLabel}>
					<span>{dashboardUiCopy.teacherAssignmentCreate.personalized.personalizedShare}</span>
					<input class={styles.textInput} type="number" min="0" max="90" value={props.form.personalizedRatio} onInput={props.onInput("personalizedRatio")} />
				</label>

				<label class={styles.fieldLabel}>
					<span>{dashboardUiCopy.teacherAssignmentCreate.personalized.personalizedDifficulty}</span>
					<select class={styles.selectInput} value={props.form.personalizedDifficulty} onInput={props.onInput("personalizedDifficulty")}>
						<For each={GENERATION_DIFFICULTY_OPTIONS}>{(option) => <option value={option.value}>{option.label}</option>}</For>
					</select>
				</label>

				<label class={styles.fieldLabel}>
					<span>{dashboardUiCopy.teacherAssignmentCreate.personalized.subjectLabel}</span>
					<input class={styles.textInput} value={props.form.subject} onInput={props.onInput("subject")} placeholder={dashboardUiCopy.teacherAssignmentCreate.personalized.subjectPlaceholder} />
				</label>

				<label class={styles.fieldLabel}>
					<span>{dashboardUiCopy.teacherAssignmentCreate.personalized.seed}</span>
					<input class={styles.textInput} type="number" step="1" value={props.form.seed} onInput={props.onInput("seed")} placeholder={dashboardUiCopy.teacherAssignmentCreate.personalized.seedPlaceholder} />
				</label>
			</div>

			<p class={styles.generatorNote}>
				Each student will receive {props.mixedGenerationQuestionCount || 0} questions with roughly {props.mixedGenerationRatioLabel} and the rest from the main topic.
			</p>
		</Show>
	</div>
);

type SharedGenerationSectionProps = {
	form: QuestionGenerationForm;
	isGenerating: boolean;
	isSubmitting: boolean;
	onInput: (field: keyof QuestionGenerationForm) => InputHandler;
	onGenerate: (event: Event) => void;
};

export const SharedGenerationSection: Component<SharedGenerationSectionProps> = (props) => (
	<div class={styles.generatorPanel}>
		<div class={styles.questionPickerHeader}>
			<div>
				<h3>{dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.title}</h3>
				<p>Create RNG-based shared questions by topic and difficulty, then attach them into this assignment when you want the whole class to receive the same set.</p>
			</div>
			<small>{dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.autoSelected}</small>
		</div>

		<div class={styles.fieldGrid}>
			<label class={styles.fieldLabel}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.topic}</span>
				<select class={styles.selectInput} value={props.form.topic} onInput={props.onInput("topic")}>
					<For each={GENERATION_TOPIC_OPTIONS}>{(option) => <option value={option.value}>{option.label}</option>}</For>
				</select>
			</label>

			<label class={styles.fieldLabel}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.difficulty}</span>
				<select class={styles.selectInput} value={props.form.difficulty} onInput={props.onInput("difficulty")}>
					<For each={GENERATION_DIFFICULTY_OPTIONS}>{(option) => <option value={option.value}>{option.label}</option>}</For>
				</select>
			</label>

			<label class={styles.fieldLabel}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.count}</span>
				<input class={styles.textInput} type="number" min="1" max="25" value={props.form.count} onInput={props.onInput("count")} />
			</label>

			<label class={styles.fieldLabel}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.seed}</span>
				<input class={styles.textInput} type="number" step="1" value={props.form.seed} onInput={props.onInput("seed")} placeholder={dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.seedPlaceholder} />
			</label>
		</div>

		<div class={styles.generatorActions}>
			<button type="button" class={styles.secondaryAction} onClick={props.onGenerate} disabled={props.isGenerating || props.isSubmitting}>
				{props.isGenerating ? dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.generating : dashboardUiCopy.teacherAssignmentCreate.sharedGeneration.generateQuestions}
			</button>
			<p class={styles.generatorNote}>Use the same seed later if you want to recreate the same generated set.</p>
		</div>
	</div>
);

type QuestionBankSectionProps = {
	questions: TeacherAssignmentSetupData["questions"];
	loading: boolean;
	mixedGenerationEnabled: boolean;
	selectedQuestionIds: number[];
	onToggle: (questionId: number) => InputHandler;
};

export const QuestionBankSection: Component<QuestionBankSectionProps> = (props) => (
	<div class={styles.questionPicker}>
		<div class={styles.questionPickerHeader}>
			<div>
				<h3>{dashboardUiCopy.teacherAssignmentCreate.questionBank.title}</h3>
				<p>{props.mixedGenerationEnabled ? "Optional shared questions. Leave these unselected if you want this homework to rely only on per-student mixed generation." : "Select the questions you want to include in this assignment."}</p>
			</div>
			<small>{props.questions.length} {dashboardUiCopy.teacherAssignmentCreate.questionBank.availableSuffix}</small>
		</div>

		<Show when={props.loading}>
			<div class={styles.questionEmptyState}>{dashboardUiCopy.teacherAssignmentCreate.questionBank.loading}</div>
		</Show>

		<Show when={!props.loading && !props.questions.length}>
			<div class={styles.questionEmptyState}>{dashboardUiCopy.teacherAssignmentCreate.questionBank.empty}</div>
		</Show>

		<div class={styles.questionList}>
			<For each={props.questions}>
				{(question) => (
					<label class={styles.questionCard}>
						<div class={styles.questionCheck}>
							<input type="checkbox" checked={props.selectedQuestionIds.includes(question.id)} onChange={props.onToggle(question.id)} />
						</div>
						<div class={styles.questionCopy}>
							<div class={styles.questionMeta}>
								<span>{question.subjectLabel}</span>
								<span>{question.difficultyLabel}</span>
								<span>{question.sourceLabel}</span>
								<span>{question.statusLabel}</span>
							</div>
							<strong>{question.title}</strong>
							<p>{question.promptPreview}</p>
						</div>
					</label>
				)}
			</For>
		</div>
	</div>
);

type SubmissionSectionProps = {
	isSubmitting: boolean;
	errorMessage: string | null;
	successMessage: string | null;
	onReset: JSX.EventHandlerUnion<HTMLButtonElement, MouseEvent>;
};

export const SubmissionSection: Component<SubmissionSectionProps> = (props) => (
	<>
	<div class={styles.formActions}>
			<button type="submit" class={styles.primaryAction} disabled={props.isSubmitting}>
				{props.isSubmitting ? dashboardUiCopy.teacherAssignmentCreate.submission.creating : dashboardUiCopy.teacherAssignmentCreate.submission.createAssignment}
			</button>
			<button type="button" class={styles.secondaryAction} onClick={props.onReset} disabled={props.isSubmitting}>
				{dashboardUiCopy.teacherAssignmentCreate.submission.resetForm}
			</button>
		</div>

		<Show when={props.errorMessage}>
			<p class={`${styles.feedbackMessage} ${styles.feedbackError}`}>{props.errorMessage}</p>
		</Show>

		<Show when={props.successMessage}>
			<p class={`${styles.feedbackMessage} ${styles.feedbackSuccess}`}>{props.successMessage}</p>
		</Show>
	</>
);

type SetupSummarySectionProps = {
	classroomName: string;
	rosterLabel: string;
	mixedGenerationEnabled: boolean;
	mixedGenerationQuestionCount: number;
	selectedQuestionCount: number;
};

export const SetupSummarySection: Component<SetupSummarySectionProps> = (props) => (
	<aside class={styles.setupSummaryCard}>
		<h2>{dashboardUiCopy.teacherAssignmentCreate.summary.title}</h2>
		<div class={styles.summaryList}>
			<div class={styles.summaryRow}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.summary.classroom}</span>
				<strong>{props.classroomName || dashboardUiCopy.teacherAssignmentCreate.summary.notChosenYet}</strong>
			</div>
			<div class={styles.summaryRow}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.summary.roster}</span>
				<strong>{props.rosterLabel || dashboardUiCopy.teacherAssignmentCreate.summary.chooseClassroom}</strong>
			</div>
			<div class={styles.summaryRow}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.summary.questions}</span>
				<strong>{props.mixedGenerationEnabled ? `${props.mixedGenerationQuestionCount || 0} per student` : `${props.selectedQuestionCount} selected`}</strong>
			</div>
			<div class={styles.summaryRow}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.summary.mode}</span>
				<strong>{props.mixedGenerationEnabled ? dashboardUiCopy.teacherAssignmentCreate.summary.mixedPersonalized : dashboardUiCopy.teacherAssignmentCreate.summary.sharedQuestionSet}</strong>
			</div>
			<div class={styles.summaryRow}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.summary.passThreshold}</span>
				<strong>{FIXED_PASS_THRESHOLD_LABEL}</strong>
			</div>
			<div class={styles.summaryRow}>
				<span>{dashboardUiCopy.teacherAssignmentCreate.summary.delivery}</span>
				<strong>{dashboardUiCopy.teacherAssignmentCreate.summary.liveAssignment}</strong>
			</div>
		</div>

		<p class={styles.setupNote}>
			{props.mixedGenerationEnabled
				? "This flow creates live homework immediately and generates a mixed personalized question set for each assigned student during publish."
				: "This flow creates live homework immediately and assigns the selected shared question set to the selected classroom. Editing an existing assignment later will need a backend update route."}
		</p>
	</aside>
);
