// Path: Frontend/src/components/dashboard/shared/dashboard.data.ts

import rawDataset from "../../../../../Mock-Data/dataset.json";
import { getAssignmentWorkHref, getDashboardAssignmentsHref, getDashboardHomeHref, getDashboardMessagesHref, getDashboardPracticeHref, getDashboardProgressHref, getDashboardSettingsHref } from "../../../lib/routes";
import type { DashboardHomeShellData, TopbarMessageItem } from "./dashboard-types";

type Dataset = {
	_meta: {
		reference_today: string;
	};
	classroom: {
		name: string;
		invite_code: string;
		target_level: number;
	};
	tutor: {
		fullname: string;
		role: string;
	};
	students: Array<{
		id: number;
		fullname: string;
		_persona: string;
	}>;
	assignments: Array<{
		id: number;
		name: string;
		topic: string;
		due_date: number;
	}>;
	assignment_assignees: Array<{
		id: number;
		assignment_id: number;
		student_id: number;
		status: "NOT_STARTED" | "IN_PROGRESS" | "SUBMITTED";
		total_marks: number;
	}>;
	student_answers: Array<{
		assignee_id: number;
		_is_correct: boolean;
		_question_topic: string;
		_answered_at: number;
	}>;
	activity_logs: Array<{
		timestamp: number;
		duration_seconds: number;
		_student_id: number;
	}>;
};

type StudentAssignment = Dataset["assignment_assignees"][number] & {
	assignment: Dataset["assignments"][number];
	answerCount: number;
	accuracy: number;
};

const dataset = rawDataset as Dataset;
const referenceTime = new Date(`${dataset._meta.reference_today}T00:00:00Z`).getTime();
const msPerDay = 1000 * 60 * 60 * 24;
const defaultStudentId = 201;

const initialsFor = (name: string) =>
	name
		.split(" ")
		.slice(0, 2)
		.map((part) => part[0])
		.join("")
		.toUpperCase();

const formatLastSeen = (timestamp: number) => {
	const dayDiff = Math.max(0, Math.round((referenceTime - timestamp) / msPerDay));
	if (dayDiff <= 0) return "today";
	if (dayDiff === 1) return "yesterday";
	return `${dayDiff} days ago`;
};

const daysUntil = (timestamp: number) => Math.max(0, Math.ceil((timestamp - referenceTime) / msPerDay));

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

const students = dataset.students;
const assignments = [...dataset.assignments].sort((left, right) => left.due_date - right.due_date);
const assignees = dataset.assignment_assignees;
const answers = dataset.student_answers;
const activityLogs = dataset.activity_logs;

const student = students.find((entry) => entry.id === defaultStudentId) ?? students[0];
const firstName = student.fullname.split(" ")[0];

const assignmentById = new Map(assignments.map((assignment) => [assignment.id, assignment]));
const assigneeById = new Map(assignees.map((assignee) => [assignee.id, assignee]));

const studentAnswers = answers.filter((answer) => assigneeById.get(answer.assignee_id)?.student_id === student.id);
const studentLogs = activityLogs.filter((log) => log._student_id === student.id);

const studentAssignments: StudentAssignment[] = assignees
	.filter((assignee) => assignee.student_id === student.id)
	.map((assignee) => {
		const assignment = assignmentById.get(assignee.assignment_id);
		if (!assignment) throw new Error(`Missing assignment ${assignee.assignment_id}`);

		const assignmentAnswers = studentAnswers.filter((answer) => answer.assignee_id === assignee.id);
		const answerCount = assignmentAnswers.length;
		const correct = assignmentAnswers.filter((answer) => answer._is_correct).length;

		return {
			...assignee,
			assignment,
			answerCount,
			accuracy: answerCount > 0 ? Math.round((correct / answerCount) * 100) : 0,
		};
	})
	.sort((left, right) => left.assignment.due_date - right.assignment.due_date);

const totalCorrectAnswers = studentAnswers.filter((answer) => answer._is_correct).length;
const overallAccuracy = studentAnswers.length > 0 ? Math.round((totalCorrectAnswers / studentAnswers.length) * 100) : 0;
const latestActivityTime = studentLogs.length > 0 ? Math.max(...studentLogs.map((log) => log.timestamp)) : referenceTime;

const inProgressAssignments = studentAssignments.filter((assignment) => assignment.status === "IN_PROGRESS");
const notStartedAssignments = studentAssignments.filter((assignment) => assignment.status === "NOT_STARTED");
const pendingAssignments = studentAssignments.filter((assignment) => assignment.status !== "SUBMITTED");
const currentAssignment = inProgressAssignments[0] ?? notStartedAssignments[0] ?? studentAssignments[studentAssignments.length - 1];
const nextNotStartedAssignment = notStartedAssignments[0] ?? currentAssignment;

const topicBuckets = new Map<string, { correct: number; total: number }>();
for (const answer of studentAnswers) {
	const bucket = topicBuckets.get(answer._question_topic) ?? { correct: 0, total: 0 };
	bucket.correct += Number(answer._is_correct);
	bucket.total += 1;
	topicBuckets.set(answer._question_topic, bucket);
}

const topicPerformance = [...topicBuckets.entries()].map(([label, bucket]) => ({
	label,
	value: Math.round((bucket.correct / bucket.total) * 100),
	total: bucket.total,
}));

const weakestTopic = [...topicPerformance].sort((left, right) => left.value - right.value || right.total - left.total)[0];

const assignmentShortName = (assignment: StudentAssignment | undefined) => assignment?.assignment.name.replace("HW", "H").split("—")[0].trim() ?? "Task";

export const classroomSummary: DashboardHomeShellData["classroomSummary"] = {
	name: dataset.classroom.name,
	targetLevel: dataset.classroom.target_level,
	inviteCode: dataset.classroom.invite_code,
	tutorName: dataset.tutor.fullname,
	tutorRole: "Lead tutor",
	tutorInitials: initialsFor(dataset.tutor.fullname),
};

export const sidebarLinks: DashboardHomeShellData["sidebarLinks"] = [
	{ label: "Home", detail: "Today", icon: "⌂", href: getDashboardHomeHref("student"), active: true },
	{ label: "Assignments", detail: `${pendingAssignments.length} live`, icon: "✓", href: getDashboardAssignmentsHref("student") },
	{ label: "Progress", detail: `${overallAccuracy}% accuracy`, icon: "↗", href: getDashboardProgressHref() },
	{ label: "Practice", detail: weakestTopic?.label ?? "Mixed skills", icon: "✦", href: getDashboardPracticeHref() },
	{ label: "Messages", detail: dataset.tutor.fullname.split(" ")[0], icon: "✉", href: getDashboardMessagesHref("student") },
	{ label: "Settings", detail: "Profile & goals", icon: "⋯", href: getDashboardSettingsHref("student") },
];

export const sidebarSupport: DashboardHomeShellData["sidebarSupport"] = {
	avatars: [assignmentShortName(currentAssignment), weakestTopic?.label.slice(0, 2).toUpperCase() ?? "WK", assignmentShortName(nextNotStartedAssignment)],
	title: "Today’s study plan",
	description: currentAssignment
		? `Pick up ${assignmentShortName(currentAssignment)}, spend 15 minutes on ${weakestTopic?.label ?? "your focus topic"}, then start ${assignmentShortName(nextNotStartedAssignment)} while it still feels easy.`
		: "Open your next task and build a short, focused study block around it.",
	buttonLabel: "Open my plan",
	buttonHref: currentAssignment ? getAssignmentWorkHref(currentAssignment.assignment.id) : getDashboardAssignmentsHref("student"),
};

export const topbarSummary: DashboardHomeShellData["topbarSummary"] = {
	searchPlaceholder: "Search assignments, hints, or question topics",
	profileName: student.fullname,
	profileRole: `${dataset.classroom.name} · Student`,
	profileBadge: initialsFor(student.fullname),
	notificationCount: 0,
	messageCount: 3,
};

export const topbarMessages: TopbarMessageItem[] = [
	{
		sender: dataset.tutor.fullname,
		initials: initialsFor(dataset.tutor.fullname),
		preview: `Let’s spend the next session tightening up ${weakestTopic?.label?.toLowerCase() ?? "your focus topic"}. A couple of calm wins here should help a lot.`,
		timestamp: "Today",
		actionHref: getDashboardMessagesHref("student"),
	},
	{
		sender: currentAssignment ? assignmentShortName(currentAssignment) : "Assignment check-in",
		initials: currentAssignment ? assignmentShortName(currentAssignment) : "AC",
		preview: currentAssignment
			? currentAssignment.status === "SUBMITTED"
				? "Nice work finishing this one. Open the review and tighten any missed marks."
				: `${currentAssignment.answerCount} questions are already done. Finish it before ${formatDueDate(currentAssignment.assignment.due_date)} while it still feels familiar.`
			: "Open your assignments to pick the next best task.",
		timestamp: currentAssignment ? (currentAssignment.status === "SUBMITTED" ? "Yesterday" : `${daysUntil(currentAssignment.assignment.due_date)}d left`) : formatLastSeen(latestActivityTime),
		actionHref: currentAssignment ? getAssignmentWorkHref(currentAssignment.assignment.id) : getDashboardAssignmentsHref("student"),
	},
	{
		sender: "Study coach",
		initials: "SC",
		preview: `End today with one easier win after you practise ${weakestTopic?.label?.toLowerCase() ?? "your focus topic"}.`,
		timestamp: formatLastSeen(latestActivityTime),
		actionHref: getDashboardProgressHref(),
	},
];
