import type { ApiReviewQueueItem } from "../../../lib/api-types";
import {
	getDashboardAssignmentsHref,
	getDashboardClassroomsHref,
	getDashboardHomeHref,
	getDashboardMessagesHref,
	getDashboardSettingsHref,
} from "../../../lib/routes";
import type { DashboardHomeShellData, TopbarMessageItem } from "../shared/dashboard-types";
import type { TeacherClassroomRedoAssignmentItem } from "./dashboard-teacher-classroom-detail.types";

export const initialsFor = (name: string) =>
	name
		.split(/\s+/)
		.filter(Boolean)
		.slice(0, 2)
		.map((part) => part[0])
		.join("")
		.toUpperCase();

export const formatShortDate = (value: string | null | undefined, fallback = "No due date") => {
	if (!value) return fallback;

	return new Intl.DateTimeFormat("en-GB", {
		month: "short",
		day: "numeric",
	}).format(new Date(value));
};

export const formatRelativeTime = (value: string | null | undefined, fallback = "No recent update") => {
	if (!value) return fallback;

	const deltaMs = Date.now() - new Date(value).getTime();
	const deltaMinutes = Math.max(0, Math.round(deltaMs / (1000 * 60)));
	if (deltaMinutes < 60) return `${deltaMinutes || 1}m ago`;
	const deltaHours = Math.round(deltaMinutes / 60);
	if (deltaHours < 24) return `${deltaHours}h ago`;
	const deltaDays = Math.round(deltaHours / 24);
	if (deltaDays < 7) return `${deltaDays}d ago`;
	return formatShortDate(value, fallback);
};

export const buildTeacherShell = (
	classroomName: string,
	inviteCode: string | null | undefined,
	classroomCount: number,
	needsReviewCount: number,
): DashboardHomeShellData => ({
	classroomSummary: {
		name: classroomName,
		inviteCode: inviteCode?.trim() || undefined,
		tutorName: "Teacher workspace",
		tutorRole: "Teaching dashboard",
		tutorInitials: "TA",
	},
	sidebarLinks: [
		{ label: "Home", detail: "Teaching overview", icon: "OV", href: getDashboardHomeHref("teacher") },
		{ label: "Assignments", detail: "Homework setup", icon: "AS", href: getDashboardAssignmentsHref("teacher") },
		{ label: "Classrooms", detail: "Roster & codes", icon: "CL", href: getDashboardClassroomsHref("teacher"), active: true },
		{ label: "Messages", detail: "Inbox & follow-up", icon: "MS", href: getDashboardMessagesHref("teacher") },
		{ label: "Settings", detail: "Profile & preferences", icon: "ST", href: getDashboardSettingsHref("teacher") },
	],
	sidebarSupport: {
		avatars: ["CL", "RQ", "TA"],
		title: "Teaching flow",
		description:
			needsReviewCount > 0
				? `${needsReviewCount} submission${needsReviewCount === 1 ? " is" : "s are"} still waiting in the review queue.`
				: `${classroomCount} classroom${classroomCount === 1 ? " is" : "s are"} connected right now.`,
		buttonLabel: needsReviewCount > 0 ? "Open assignments" : "Back to classrooms",
		buttonHref: needsReviewCount > 0 ? getDashboardAssignmentsHref("teacher") : getDashboardClassroomsHref("teacher"),
	},
	topbarSummary: {
		searchPlaceholder: "Search classes, assignments, or students",
		profileName: "Teacher",
		profileRole: "Teaching dashboard",
		profileBadge: "TA",
		notificationCount: 0,
		messageCount: 0,
	},
	topbarNotifications: [],
	topbarMessages: [] as TopbarMessageItem[],
});

export const queueStatusLabel = (item: ApiReviewQueueItem) => {
	if (item.next_step_outcome === "redo") return "Redo set";
	if (item.next_step_outcome === "accept") return "Accepted";
	if (item.next_step_outcome === "support") return "Support next";
	if (item.review_status === "submitted") return "Needs review";
	if (item.review_status === "reviewed") return "Reviewed";
	if (item.review_status === "in_progress" || item.answered_questions > 0 || item.reviewed_questions > 0) return "In progress";
	return "Not started";
};

export const queueStatusTone = (item: ApiReviewQueueItem): TeacherClassroomRedoAssignmentItem["statusTone"] => {
	if (item.next_step_outcome === "accept") return "success";
	if (item.next_step_outcome === "redo" || item.next_step_outcome === "support" || item.review_status === "submitted") return "review";
	if (item.review_status === "in_progress" || item.answered_questions > 0 || item.reviewed_questions > 0) return "progress";
	return "muted";
};

export const studentNote = (submittedCount: number, activeRedoCount: number, closedRedoCount: number) => {
	if (submittedCount > 0) return `${submittedCount} redo assignment${submittedCount === 1 ? " is" : "s are"} waiting for review.`;
	if (activeRedoCount > 0) return `${activeRedoCount} live redo assignment${activeRedoCount === 1 ? "" : "s"} currently assigned.`;
	if (closedRedoCount > 0) return `${closedRedoCount} closed redo assignment${closedRedoCount === 1 ? "" : "s"} available for reference.`;
	return "No individual redo assignments for this student yet.";
};

export const formatCombinedScoreLabel = (combinedScore: number | null, scoredAssignments: number) => {
	if (combinedScore == null || scoredAssignments <= 0) {
		return "No scored assignments yet";
	}

	return `Combined score ${combinedScore.toFixed(1)} across ${scoredAssignments} assignment${scoredAssignments === 1 ? "" : "s"}`;
};
