import rawAssignments from "../../../../Mock-Data/assignments.json";
import rawAssignmentAssignees from "../../../../Mock-Data/assignment_assignees.json";
import rawAssignmentQuestions from "../../../../Mock-Data/assignment_questions.json";
import rawQuestionBank from "../../../../Mock-Data/question_bank.json";
import rawStudentAnswers from "../../../../Mock-Data/student_answers.json";
import rawStudents from "../../../../Mock-Data/students.json";
import rawClassroom from "../../../../Mock-Data/classroom.json";

type Assignment = {
	id: number;
	name: string;
	topic: string;
	due_date: number;
	status: "DRAFT" | "PUBLISHED" | "CLOSED";
	maximum_marks: number;
};

type AssignmentAssignee = {
	id: number;
	assignment_id: number;
	student_id: number;
	status: "NOT_STARTED" | "IN_PROGRESS" | "SUBMITTED";
	total_marks: number;
	started_at: number | null;
	submitted_at: number | null;
};

type AssignmentQuestion = {
	id: number;
	assignment_id: number;
	question_bank_id: number;
	question_order: number;
	maximum_marks: number;
};

type QuestionBankItem = {
	id: number;
	topic: string;
	sub_topic: string | null;
	difficulty: "EASY" | "MEDIUM" | "HARD";
	question_text: string;
	correct_answer: string;
	step_by_step_solution: string | null;
};

type StudentAnswer = {
	assignee_id: number;
	assignment_question_id: number;
	extracted_answer: string;
	ai_reasoning: string;
	_solve_mode: "just_answer" | "step_by_step" | "solve_together" | "handwritten";
	_is_correct: boolean;
	_time_on_task_seconds: number;
};

type Student = {
	id: number;
	fullname: string;
	_persona: string;
};

type ClassroomFile = {
	classroom: {
		name: string;
		target_level: number;
	};
	tutor: {
		fullname: string;
	};
};

export type AssignmentPageData = {
	id: number;
	title: string;
	topic: string;
	status: "NOT_STARTED" | "IN_PROGRESS" | "SUBMITTED";
	statusLabel: string;
	dueLabel: string;
	studentName: string;
	classroomName: string;
	tutorName: string;
	headline: string;
	description: string;
	primaryAction: string;
	primaryHref: string;
	stats: Array<{ label: string; value: string }>;
	coachCard: {
		title: string;
		description: string;
		items: string[];
	};
	questions: Array<{
		id: number;
		order: number;
		prompt: string;
		topic: string;
		subTopic: string | null;
		difficulty: "EASY" | "MEDIUM" | "HARD";
		marks: number;
		statusLabel: string;
		statusTone: "success" | "warning" | "muted";
		responseLabel: string;
		responseValue: string;
		feedback: string;
		solveModeLabel?: string;
		initialAnswer?: string;
		initialSolveMode?: "just_answer" | "step_by_step" | "solve_together" | "handwritten";
		showAnswerKey: boolean;
		correctAnswer: string;
	}>;
};

const assignments = rawAssignments as Assignment[];
const assignmentAssignees = rawAssignmentAssignees as AssignmentAssignee[];
const assignmentQuestions = rawAssignmentQuestions as AssignmentQuestion[];
const questionBank = rawQuestionBank as QuestionBankItem[];
const studentAnswers = rawStudentAnswers as StudentAnswer[];
const students = rawStudents as Student[];
const classroomFile = rawClassroom as ClassroomFile;

const defaultStudentId = 201;

const assignmentById = new Map(assignments.map((entry) => [entry.id, entry]));
const questionById = new Map(questionBank.map((entry) => [entry.id, entry]));
const student = students.find((entry) => entry.id === defaultStudentId) ?? students[0];

const formatDate = (timestamp: number) =>
	new Intl.DateTimeFormat("en-GB", {
		weekday: "short",
		month: "short",
		day: "numeric",
	}).format(new Date(timestamp));

const formatSolveMode = (value: StudentAnswer["_solve_mode"]) => {
	switch (value) {
		case "just_answer":
			return "Just answer";
		case "step_by_step":
			return "Step by step";
		case "solve_together":
			return "Solve together";
		case "handwritten":
			return "Handwritten";
	}
};

const personaHint = (persona: string) => {
	switch (persona) {
		case "fraction_inversion":
			return "Slow down on fraction rules and check each step before moving on.";
		case "place_value_gaps":
			return "Check place value carefully before you calculate the final answer.";
		case "rushed_careless":
			return "Pause before submitting so small slips do not cost easy marks.";
		case "solve_together_dependent":
			return "Try one independent attempt first, then ask for guided help if you need it.";
		case "word_problem_weak":
			return "Underline the key numbers and turn the sentence into a maths step first.";
		default:
			return "Work through one question at a time and keep your method tidy.";
	}
};

export const getAssignmentPageData = (assignmentId: number): AssignmentPageData | null => {
	const assignment = assignmentById.get(assignmentId);
	if (!assignment) return null;

	const assignee = assignmentAssignees.find((entry) => entry.assignment_id === assignment.id && entry.student_id === student.id);
	if (!assignee) return null;

	const assignmentQuestionRows = assignmentQuestions
		.filter((entry) => entry.assignment_id === assignment.id)
		.sort((left, right) => left.question_order - right.question_order)
		.map((entry) => {
			const question = questionById.get(entry.question_bank_id);
			if (!question) throw new Error(`Missing question bank record ${entry.question_bank_id}`);

			const answer = studentAnswers.find((studentAnswer) => studentAnswer.assignee_id === assignee.id && studentAnswer.assignment_question_id === entry.id);

			return { entry, question, answer };
		});

	const answeredCount = assignmentQuestionRows.filter((row) => !!row.answer).length;
	const correctCount = assignmentQuestionRows.filter((row) => row.answer?._is_correct).length;
	const accuracy = answeredCount > 0 ? Math.round((correctCount / answeredCount) * 100) : 0;

	const statusLabel = assignee.status === "SUBMITTED" ? "Submitted" : assignee.status === "IN_PROGRESS" ? "In progress" : "Not started";
	const primaryAction = assignee.status === "SUBMITTED" ? "Review assignment" : assignee.status === "IN_PROGRESS" ? "Continue assignment" : "Start assignment";

	const questions = assignmentQuestionRows.map(({ entry, question, answer }) => ({
		id: entry.id,
		order: entry.question_order,
		prompt: question.question_text,
		topic: question.topic,
		subTopic: question.sub_topic,
		difficulty: question.difficulty,
		marks: entry.maximum_marks,
		statusLabel: answer ? (answer._is_correct ? "Correct" : "Needs review") : "Not answered",
		statusTone: answer ? (answer._is_correct ? "success" : "warning") : "muted",
		responseLabel: answer ? "Your latest answer" : "Status",
		responseValue: answer ? answer.extracted_answer : "No attempt yet",
		feedback: answer ? answer.ai_reasoning : "This sample question is ready when you are.",
		solveModeLabel: answer ? formatSolveMode(answer._solve_mode) : undefined,
		initialAnswer: answer?.extracted_answer,
		initialSolveMode: answer?._solve_mode,
		showAnswerKey: assignee.status === "SUBMITTED",
		correctAnswer: question.correct_answer,
	}));

	return {
		id: assignment.id,
		title: assignment.name,
		topic: assignment.topic,
		status: assignee.status,
		statusLabel,
		dueLabel: formatDate(assignment.due_date),
		studentName: student.fullname,
		classroomName: classroomFile.classroom.name,
		tutorName: classroomFile.tutor.fullname,
		headline:
			assignee.status === "SUBMITTED"
				? `Review how you did in ${assignment.topic}`
				: assignee.status === "IN_PROGRESS"
					? `Keep going — you are already part way through`
					: `Start this assignment with a steady first pass`,
		description:
			assignee.status === "SUBMITTED"
				? `You scored ${assignee.total_marks}/${assignment.maximum_marks}. Use the sample questions below to revisit what felt easy and what still needs another try.`
				: assignee.status === "IN_PROGRESS"
					? `You have answered ${answeredCount} of ${assignmentQuestionRows.length} questions. Finish the rest while the topic is still fresh.`
					: `This assignment has ${assignmentQuestionRows.length} sample questions. Start with the easier wins, then work up to the harder ones.`,
		primaryAction,
		primaryHref: `/assignment/${assignment.id}/work`,
		stats: [
			{ label: "Status", value: statusLabel },
			{ label: "Due", value: formatDate(assignment.due_date) },
			{ label: "Questions", value: `${assignmentQuestionRows.length}` },
			{ label: assignee.status === "SUBMITTED" ? "Score" : "Answered", value: assignee.status === "SUBMITTED" ? `${assignee.total_marks}/${assignment.maximum_marks}` : `${answeredCount}/${assignmentQuestionRows.length}` },
		],
		coachCard: {
			title: "How to approach this one",
			description: personaHint(student._persona),
			items: [
				`${assignment.topic} focus`,
				`${accuracy}% accuracy so far`,
				`${correctCount} correct answers logged`,
			],
		},
		questions,
	};
};
