import {
	getAssignmentReviewHref,
	getAssignmentWorkHref,
	getDashboardAssignmentsHref,
	getDashboardMessagesHref,
	getDashboardPracticeHref,
	getDashboardProgressHref,
	getDashboardSettingsHref,
	getDashboardHomeHref,
} from "../../../lib/routes";
import { apiFetchJson } from "../../../lib/api";
import type { ApiAssignment, ApiAssignmentStudentQuestionDetail, ApiClassroom, ApiListResponse, ApiUser } from "../../../lib/api-types";
import { studentDashboardLabels } from "../../../content/dashboard-labels";
import type { DashboardHomeData } from "../shared/dashboard-types";
import {
	buildAssignmentCards,
	buildDerivedAssignments,
	buildProgressSeries,
	buildTopicAggregates,
	buildUsageItems,
	daysUntil,
	formatAssignmentBadge,
	formatAssignmentShortTitle,
	formatDueCountdown,
	formatRelativeTime,
	initialsFor,
	masteryTones,
	sortByDueDate,
	toneAt,
} from "./dashboard-home.helpers";

export const getDashboardHomeData = async (studentId: number): Promise<DashboardHomeData> => {
	const assignmentsResponse = await apiFetchJson<ApiListResponse<ApiAssignment>>(`/api/students/${studentId}/assignments`);
	const assignments = assignmentsResponse.data;

	const questionEntries = await Promise.all(
		assignments.map(async (assignment) => ({
			assignmentId: assignment.id,
			questions: (await apiFetchJson<ApiListResponse<ApiAssignmentStudentQuestionDetail>>(`/api/assignments/${assignment.id}/students/${studentId}/questions`)).data,
		})),
	);

	const questionsByAssignment = new Map(questionEntries.map((entry) => [entry.assignmentId, entry.questions]));
	const derivedAssignments = buildDerivedAssignments(assignments, questionsByAssignment);
	const activeAssignments = derivedAssignments.filter((assignment) => assignment.status !== "SUBMITTED").sort(sortByDueDate);
	const completedAssignments = derivedAssignments.filter((assignment) => assignment.status === "SUBMITTED").sort(sortByDueDate);
	const currentAssignment = activeAssignments.find((assignment) => assignment.status === "IN_PROGRESS") ?? activeAssignments[0] ?? completedAssignments[0] ?? null;
	const nextDueAssignment = activeAssignments.find((assignment) => Boolean(assignment.assignment.due_at)) ?? null;
	const nextAssignment = activeAssignments.find((assignment) => assignment.assignment.id !== currentAssignment?.assignment.id) ?? null;
	const topicAggregates = buildTopicAggregates(derivedAssignments);
	const weakestTopic = topicAggregates[0] ?? null;
	const strongestTopic = topicAggregates.slice().sort((left, right) => right.completion - left.completion || right.total - left.total)[0] ?? null;
	const latestTouch =
		derivedAssignments
			.map((assignment) => assignment.lastTouchedAt)
			.filter((value): value is string => Boolean(value))
			.sort((left, right) => new Date(right).getTime() - new Date(left).getTime())[0] ?? null;

	const totalQuestions = derivedAssignments.reduce((sum, assignment) => sum + assignment.questions.length, 0);
	const totalAnswered = derivedAssignments.reduce((sum, assignment) => sum + assignment.answeredCount, 0);
	const totalReviewed = derivedAssignments.reduce((sum, assignment) => sum + assignment.reviewedCount, 0);
	const overallProgress = totalQuestions > 0 ? Math.round((totalReviewed / totalQuestions) * 100) : 0;
	const answerCoverage = totalQuestions > 0 ? Math.round((totalAnswered / totalQuestions) * 100) : 0;
	const remainingCount = totalQuestions - totalAnswered;
	const inProgressCount = derivedAssignments.filter((assignment) => assignment.status === "IN_PROGRESS").length;
	const notStartedCount = derivedAssignments.filter((assignment) => assignment.status === "NOT_STARTED").length;

	let teacher: ApiUser | null = null;
	let classroom: ApiClassroom | null = null;
	if (currentAssignment?.assignment.teacher_id) {
		teacher = await apiFetchJson<ApiUser>(`/api/users/${currentAssignment.assignment.teacher_id}`);
		const classroomsResponse = await apiFetchJson<ApiListResponse<ApiClassroom>>(`/api/teachers/${currentAssignment.assignment.teacher_id}/classrooms`);
		classroom = classroomsResponse.data.find((entry) => entry.id === currentAssignment.assignment.classroom_id) ?? classroomsResponse.data[0] ?? null;
	}

	const firstName = teacher ? teacher.full_name.split(" ")[0] : "Coach";
	const studentName = teacher?.full_name ? undefined : undefined;
	const progressSeries = buildProgressSeries(derivedAssignments);
	const currentAssignmentTitle = currentAssignment?.assignment.title ?? "your next assignment";
	const currentAssignmentShort = currentAssignment ? formatAssignmentShortTitle(currentAssignment.assignment.title, "your next task") : "your next task";
	const nextAssignmentShort = nextAssignment ? formatAssignmentShortTitle(nextAssignment.assignment.title, "another task") : "another task";
	const currentAssignmentBadge = currentAssignment ? formatAssignmentBadge(currentAssignment.assignment.title) : "NT";
	const nextAssignmentBadge = nextAssignment ? formatAssignmentBadge(nextAssignment.assignment.title) : "AT";
	const currentActionHref = currentAssignment
		? currentAssignment.status === "SUBMITTED"
			? getAssignmentReviewHref("student", currentAssignment.assignment.id)
			: getAssignmentWorkHref(currentAssignment.assignment.id)
		: getDashboardAssignmentsHref("student");
	const currentDueDays = currentAssignment && currentAssignment.status !== "SUBMITTED" && currentAssignment.assignment.due_at ? daysUntil(currentAssignment.assignment.due_at) : null;
	const nextDueDays = nextDueAssignment?.assignment.due_at ? daysUntil(nextDueAssignment.assignment.due_at) : null;
	const usageItems = buildUsageItems(totalQuestions, totalReviewed, totalAnswered, remainingCount);

	const tutorName = teacher?.full_name ?? "Your tutor";
	const tutorInitials = initialsFor(tutorName);
	const studentFirstName = "Learner";

	return {
			shell: {
				classroomSummary: {
					name: classroom?.name ?? "Live dashboard",
					targetLevel: undefined,
					inviteCode: classroom?.code ?? undefined,
					tutorName,
					tutorRole: teacher ? "Lead tutor" : "Learning support",
					tutorInitials,
				},
			sidebarLinks: [
				{ label: "Home", detail: "Today", icon: "⌂", href: getDashboardHomeHref("student"), active: true },
				{ label: "Assignments", detail: `${inProgressCount + notStartedCount} live`, icon: "✓", href: getDashboardAssignmentsHref("student") },
				{ label: "Progress", detail: `${overallProgress}% reviewed`, icon: "↗", href: getDashboardProgressHref() },
				{ label: "Practice", detail: weakestTopic?.label ?? "Mixed skills", icon: "✦", href: getDashboardPracticeHref() },
				{ label: "Messages", detail: tutorName.split(" ")[0], icon: "✉", href: getDashboardMessagesHref("student") },
				{ label: "Settings", detail: "Profile & goals", icon: "⋯", href: getDashboardSettingsHref("student") },
			],
				sidebarSupport: {
				avatars: [currentAssignmentBadge, (weakestTopic?.label ?? "Focus").slice(0, 2).toUpperCase(), nextAssignmentBadge],
				title: "Today’s study plan",
				description: currentAssignment
					? `Pick up ${currentAssignmentShort}, spend 15 minutes on ${weakestTopic?.label ?? "your current topic"}, then move into ${nextAssignmentShort} while the flow is still there.`
					: "Start with your assignment list, pick one live task, and use the dashboard to stay in a simple study rhythm.",
				buttonLabel: currentAssignment ? "Open my plan" : "See assignments",
				buttonHref: currentAssignment ? currentActionHref : getDashboardAssignmentsHref("student"),
			},
			topbarSummary: {
				searchPlaceholder: "Search assignments, hints, or question topics",
				profileName: `Student ${studentId}`,
				profileRole: classroom ? `${classroom.name} · Student` : "Student dashboard",
				profileBadge: tutorInitials,
				notificationCount: 3,
				messageCount: 3,
			},
			topbarNotifications: [
				{
					title: currentAssignment ? `${currentAssignmentShort} is your live priority` : "No live assignment yet",
					description: currentAssignment
						? currentAssignment.status === "SUBMITTED"
							? `You already finished it. Open the review and tighten any marked answers.`
							: `${currentAssignment.answeredCount}/${currentAssignment.questions.length || 0} questions touched so far. Keep the momentum going.`
						: "Open your assignments list to start the next live task.",
					timestamp: currentDueDays !== null ? formatDueCountdown(currentDueDays, "labelled") : "Today",
					href: currentAssignment ? currentActionHref : getDashboardAssignmentsHref("student"),
					tone: "blue",
				},
				{
					title: `${weakestTopic?.label ?? "Your focus topic"} needs a short pass`,
					description: weakestTopic
						? `${weakestTopic.reviewed}/${weakestTopic.total} questions are fully reviewed here. A short focused block will lift your coverage fastest.`
						: "Use a short practice block to warm up before you dive into assignment work.",
					timestamp: "Practice now",
					href: getDashboardPracticeHref(),
					tone: "yellow",
				},
				{
					title: `${tutorName.split(" ")[0]} has your next step ready`,
					description: currentAssignment
						? `Use ${currentAssignmentShort} as your anchor task, then finish on ${strongestTopic?.label ?? "a stronger topic"} for confidence.`
						: "Check your messages for study guidance and quick next-step prompts.",
					timestamp: "Today",
					href: getDashboardMessagesHref("student"),
					tone: "teal",
				},
			],
			topbarMessages: [
				{
					sender: tutorName,
					initials: tutorInitials,
					preview: weakestTopic
						? `Let’s steady ${weakestTopic.label.toLowerCase()} first, then return to ${currentAssignmentShort}.`
						: "Pick one live task and stay with it until you finish a clear chunk.",
					timestamp: "Today",
					actionHref: getDashboardMessagesHref("student"),
				},
				{
					sender: "Assignment check-in",
					initials: currentAssignmentBadge,
					preview: currentAssignment
						? currentAssignment.status === "SUBMITTED"
							? `Nice work finishing ${currentAssignmentTitle}. Revisit the review before moving on.`
							: `${currentAssignment.answeredCount}/${currentAssignment.questions.length || 0} questions are already moving. Resume while it is still fresh.`
						: "No assignment is active yet. Start with the next live task in your list.",
					timestamp: currentDueDays !== null ? formatDueCountdown(currentDueDays, "labelled") : "Soon",
					actionHref: currentAssignment ? currentActionHref : getDashboardAssignmentsHref("student"),
				},
				{
					sender: "Study coach",
					initials: "SC",
					preview: strongestTopic
						? `Finish today with ${strongestTopic.label.toLowerCase()} after you steady ${weakestTopic?.label?.toLowerCase() ?? "your main topic"}.`
						: "Finish the session with one easier win after your main assignment push.",
					timestamp: formatRelativeTime(latestTouch),
					actionHref: getDashboardProgressHref(),
				},
			],
		},
		hero: {
			heroSummary: {
				eyebrow: `Welcome back`,
				title: currentAssignment
					? currentAssignment.status === "SUBMITTED"
						? `Nice work finishing ${currentAssignmentShort}`
						: `Let’s keep ${currentAssignmentShort} moving`
					: "Your live dashboard is ready",
				description: currentAssignment
					? `You have ${completedAssignments.length} finished assignments so far. Right now, the clearest next step is to keep ${currentAssignmentShort} moving and tighten ${weakestTopic?.label ?? "your current focus"}.`
					: "Your dashboard home is now loading from the live backend. Start with one assignment and build momentum from there.",
				visualBadges: [
					`${overallProgress}% reviewed`,
					currentAssignment ? `${currentAssignmentShort} live` : "Live backend",
					weakestTopic ? `${weakestTopic.label} focus` : "Focus next",
				],
			},
			spotlightStats: [
				{ label: studentDashboardLabels.spotlight.assignmentsDone, value: `${completedAssignments.length}/${derivedAssignments.length}`, tone: "purple" },
				{ label: studentDashboardLabels.spotlight.currentFocus, value: weakestTopic?.label ?? "Mixed practice", tone: "yellow" },
				{ label: studentDashboardLabels.spotlight.bestTopic, value: strongestTopic?.label ?? "Building", tone: "blue" },
			],
			heroSideCard: {
				title: currentAssignment
					? currentAssignment.status === "SUBMITTED"
						? `Review ${currentAssignmentShort}`
						: `Pick up where you left off`
					: "Open your assignment hub",
				description: currentAssignment
					? currentAssignment.status === "SUBMITTED"
						? `${currentAssignment.reviewedCount}/${currentAssignment.questions.length || 0} questions are fully reviewed. A quick recap now will make the next task easier.`
						: `${currentAssignment.answeredCount}/${currentAssignment.questions.length || 0} questions are already done. Finish it while the method is still fresh.`
					: "No active assignment is selected yet. Head to your assignments list and start the next live task.",
				buttonLabel: currentAssignment ? (currentAssignment.status === "SUBMITTED" ? "Open review" : "Resume assignment") : "See assignments",
				buttonHref: currentAssignment ? currentActionHref : getDashboardAssignmentsHref("student"),
			},
			quickStats: [
				{ label: studentDashboardLabels.quickStats.nextDue, value: formatDueCountdown(nextDueDays) },
				{ label: studentDashboardLabels.quickStats.latestUpdate, value: formatRelativeTime(latestTouch) },
			],
		},
		assignmentCards: buildAssignmentCards(derivedAssignments).length
			? buildAssignmentCards(derivedAssignments)
			: [
				{
					title: "Start your first live assignment",
					badge: formatAssignmentBadge("Start your first live assignment"),
					lessons: "Your dashboard is connected to the backend and ready for real work.",
					accent: "blue",
					cta: "Open assignments",
					href: getDashboardAssignmentsHref("student"),
				},
			],
		activity: {
			activitySummary: {
				title: `${overallProgress}% reviewed so far`,
				note: currentAssignment
					? `${answerCoverage}% of questions have at least one answer. Use ${currentAssignmentShort} as the next push.`
					: "As you work through live assignments, your progress trend will update here from backend data.",
				badge: currentAssignment ? `${currentAssignment.answeredCount}/${currentAssignment.questions.length || 0} current` : "Live",
			},
			progressLabels: progressSeries.labels,
			progressPoints: progressSeries.points,
				highlightCards: [
					{
						value: `${completedAssignments.length}`,
						label: studentDashboardLabels.activity.completed,
						note: "Assignments fully reviewed and ready to revisit.",
						tone: "yellow",
					},
					{
						value: `${answerCoverage}%`,
						label: studentDashboardLabels.activity.answerCoverage,
						note: `${totalAnswered}/${totalQuestions || 0} questions have active work on them.`,
						tone: "pink",
					},
			],
		},
		studentSupportList: [
			{
				name: `Tighten ${weakestTopic?.label ?? "your focus topic"}`,
				meta: weakestTopic
					? `${weakestTopic.reviewed}/${weakestTopic.total} reviewed so far · quickest lift`
					: "Use one short focused block before the main assignment push.",
				initials: (weakestTopic?.label ?? "Focus").slice(0, 2).toUpperCase(),
				actionLabel: "Open practice",
				href: getDashboardPracticeHref(),
			},
			{
				name: currentAssignment ? `Finish ${currentAssignmentShort}` : "Start the next task",
				meta: currentAssignment
					? `${currentAssignment.answeredCount}/${currentAssignment.questions.length || 0} answered · best next move`
					: "Choose one live assignment and make the first small step.",
				initials: currentAssignmentBadge,
				actionLabel: currentAssignment ? "Resume work" : "See assignments",
				href: currentAssignment ? currentActionHref : getDashboardAssignmentsHref("student"),
			},
			{
				name: `Finish on ${strongestTopic?.label ?? "a stronger topic"}`,
				meta: strongestTopic
					? `${strongestTopic.completion}% reviewed here · good confidence finish`
					: "End the session with one easier win after the hard part.",
				initials: (strongestTopic?.label ?? "Win").slice(0, 2).toUpperCase(),
				actionLabel: "View progress",
				href: getDashboardProgressHref(),
			},
		],
		insights: {
			masteryTitle: "My topic coverage",
			overallTitle: "My review progress",
			overallLabel: studentDashboardLabels.insights.reviewed,
			usageTitle: "Question status mix",
			overallPassRate: overallProgress,
			topicMasteryBars: (topicAggregates.length ? topicAggregates : [{ label: "Getting started", total: 1, answered: 0, reviewed: 0, completion: 0 }]).slice(0, 5).map((topic, index) => ({
				label: topic.label,
				value: topic.completion,
				tone: toneAt(masteryTones, index),
			})),
			solveModeUsage: usageItems,
			usageSummary: {
				note: currentAssignment
					? `${remainingCount} questions still need first-pass answers. Finish ${currentAssignmentShort}, then revisit reviewed work for a cleaner close.`
					: "As backend work comes in, this panel will show how much of your live question load is answered and fully reviewed.",
			},
		},
	};
};
