// Path: Frontend/src/components/dashboard/shared/dashboard-topbar.tsx

import { A } from "@solidjs/router";
import { createEffect, createMemo, createResource, createSignal, For, onCleanup, onMount, Show, type Component } from "solid-js";
import { useAuth } from "~/context/auth/context";
import { getDashboardMessagesHref, getDashboardSettingsHref } from "../../../lib/routes";
import { getDashboardTopbarMessagesData } from "../messages/dashboard-messages.data";
import DashboardThemeToggle from "./dashboard-theme-toggle";
import styles from "./dashboard-topbar.module.scss";
import type { DashboardHomeShellData } from "./dashboard-types";
import { topbarMessages, topbarSummary } from "./dashboard.data";

type DashboardTopbarProps = {
	isSidebarOpen: boolean;
	onMenuToggle: () => void;
	data?: Pick<DashboardHomeShellData, "topbarSummary" | "topbarNotifications" | "topbarMessages">;
};

const initialsFor = (value: string) => {
	const cleaned = value.trim();
	if (!cleaned) return "U";

	const parts = cleaned.split(/\s+/).filter(Boolean);
	if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();

	return `${parts[0]?.[0] ?? ""}${parts[1]?.[0] ?? ""}`.toUpperCase();
};

const roleLabel = (role?: "student" | "teacher") => {
	if (role === "teacher") return "Teacher";
	if (role === "student") return "Student";
	return null;
};

const DashboardTopbar: Component<DashboardTopbarProps> = (props) => {
	const auth = useAuth();
	const [openMenu, setOpenMenu] = createSignal<"search" | "messages" | "profile" | null>(null);
	const currentUser = createMemo(() => (auth.isReady() ? (auth.user() ?? null) : null));
	const topbarMessagesSource = createMemo(() => {
		const user = currentUser();
		if (!user) return null;
		return { userId: user.id, role: user.role };
	});
	const [liveMessages] = createResource(topbarMessagesSource, ({ userId, role }) => getDashboardTopbarMessagesData(userId, role));
	let menuRoot: HTMLDivElement | undefined;
	const dashboardRole = createMemo(() => currentUser()?.role ?? "student");
	const inboxHref = createMemo(() => getDashboardMessagesHref(dashboardRole()));
	const settingsHref = createMemo(() => getDashboardSettingsHref(dashboardRole()));
	const summary = () => {
		const baseSummary = props.data?.topbarSummary ?? topbarSummary;
		const live = liveMessages();
		if (!live) return baseSummary;

		return {
			...baseSummary,
			messageCount: live.messageCount,
		};
	};
	const messages = () => liveMessages()?.topbarMessages ?? props.data?.topbarMessages ?? topbarMessages;
	const unreadThreadCount = () => liveMessages()?.unreadThreadCount ?? summary().messageCount;

	const toggleMenu = (menu: "messages" | "profile") => {
		setOpenMenu((current) => (current === menu ? null : menu));
	};

	const profileName = () => auth.user()?.profile.preferred_name ?? auth.user()?.full_name ?? summary().profileName;
	const profileRole = () => auth.user()?.profile.headline ?? roleLabel(auth.user()?.role) ?? summary().profileRole;
	const profileBadge = () => initialsFor(profileName() || summary().profileName);
	const profileIconUrl = () => auth.user()?.profile.profile_icon_url ?? null;
	let mobileSearchInput: HTMLInputElement | undefined;

	const handleLogout = async () => {
		await auth.logout();
		setOpenMenu(null);
		window.location.href = "/auth/login";
	};

	onMount(() => {
		const handlePointerDown = (event: MouseEvent) => {
			if (!menuRoot?.contains(event.target as Node)) {
				setOpenMenu(null);
			}
		};

		document.addEventListener("pointerdown", handlePointerDown);
		onCleanup(() => document.removeEventListener("pointerdown", handlePointerDown));
	});

	createEffect(() => {
		if (openMenu() !== "search") return;
		queueMicrotask(() => mobileSearchInput?.focus());
	});

	return (
		<header class={styles.topbar}>
			<button type="button" classList={{ [styles.menuButton]: true, [styles.menuButtonOpen]: props.isSidebarOpen }} aria-label={props.isSidebarOpen ? "Close menu" : "Open menu"} aria-expanded={props.isSidebarOpen} onClick={props.onMenuToggle}>
				<span class={styles.menuGlyph} aria-hidden="true">
					<span class={styles.menuLine} />
					<span class={styles.menuLine} />
					<span class={styles.menuLine} />
				</span>
			</button>

			<label class={styles.searchField}>
				<span class={styles.searchIcon} aria-hidden="true">
					<svg viewBox="0 0 24 24">
						<circle cx="11" cy="11" r="6" />
						<path d="M20 20l-4.2-4.2" />
					</svg>
				</span>
				<input type="search" placeholder={summary().searchPlaceholder} />
			</label>

			<div class={styles.actions} ref={menuRoot}>
				<Show when={openMenu()}>
					<button type="button" class={styles.mobileMenuBackdrop} aria-label="Close menu" tabIndex={-1} onClick={() => setOpenMenu(null)} />
				</Show>

				<div class={styles.menuGroup}>
					<button type="button" classList={{ [styles.iconButton]: true, [styles.searchToggle]: true }} aria-label="Search" aria-expanded={openMenu() === "search"} onClick={() => toggleMenu("search")}>
						<svg viewBox="0 0 24 24" aria-hidden="true">
							<circle cx="11" cy="11" r="6" />
							<path d="M20 20l-4.2-4.2" />
						</svg>
					</button>

					<Show when={openMenu() === "search"}>
						<div class={`${styles.dropdown} ${styles.searchDropdown}`}>
							<div class={styles.dropdownHeader}>
								<div>
									<p class={styles.dropdownEyebrow}>Search</p>
									<strong>Find something quickly</strong>
									<p class={styles.dropdownMeta}>{summary().searchPlaceholder}</p>
								</div>
								<div class={styles.dropdownHeaderActions}>
									<button type="button" class={styles.mobileDropdownClose} aria-label="Close search" onClick={() => setOpenMenu(null)}>
										<svg viewBox="0 0 20 20" aria-hidden="true">
											<path d="M5 5l10 10M15 5 5 15" />
										</svg>
									</button>
								</div>
							</div>

							<label class={`${styles.searchField} ${styles.searchFieldSheet}`}>
								<span class={styles.searchIcon} aria-hidden="true">
									<svg viewBox="0 0 24 24">
										<circle cx="11" cy="11" r="6" />
										<path d="M20 20l-4.2-4.2" />
									</svg>
								</span>
								<input ref={mobileSearchInput} type="search" placeholder={summary().searchPlaceholder} />
							</label>
						</div>
					</Show>
				</div>

				<DashboardThemeToggle />

				<div class={styles.menuGroup}>
					<button type="button" class={styles.iconButton} aria-label="Messages" aria-expanded={openMenu() === "messages"} onClick={() => toggleMenu("messages")}>
						<svg viewBox="0 0 24 24" aria-hidden="true">
							<path d="M4 6h16v10H8l-4 3V6Z" />
						</svg>
						<Show when={summary().messageCount > 0}>
							<span class={styles.countBadge}>{summary().messageCount}</span>
						</Show>
					</button>

					<Show when={openMenu() === "messages"}>
						<div class={styles.dropdown}>
							<div class={styles.dropdownHeader}>
								<div>
									<p class={styles.dropdownEyebrow}>Inbox</p>
									<strong>Messages</strong>
									<p class={styles.dropdownMeta}>
										{unreadThreadCount()} unread thread{unreadThreadCount() === 1 ? "" : "s"}
									</p>
								</div>
								<div class={styles.dropdownHeaderActions}>
									<A href={inboxHref()} class={styles.dropdownLink} onClick={() => setOpenMenu(null)}>
										Open inbox
									</A>
									<button type="button" class={styles.mobileDropdownClose} aria-label="Close messages menu" onClick={() => setOpenMenu(null)}>
										<svg viewBox="0 0 20 20" aria-hidden="true">
											<path d="M5 5l10 10M15 5 5 15" />
										</svg>
									</button>
								</div>
							</div>

							<div class={styles.dropdownList}>
								<Show when={messages().length} fallback={<div class={styles.emptyDropdownState}>No active threads yet.</div>}>
									<For each={messages()}>
										{(item) => (
											<A href={item.actionHref} class={styles.dropdownItem} onClick={() => setOpenMenu(null)}>
												<span class={styles.messageAvatar}>{item.initials}</span>
												<div class={styles.itemCopy}>
													<strong>{item.sender}</strong>
													<p>{item.preview}</p>
												</div>
												<small>{item.timestamp}</small>
											</A>
										)}
									</For>
								</Show>
							</div>
						</div>
					</Show>
				</div>

				<div class={styles.menuGroup}>
					<button type="button" classList={{ [styles.profileButton]: true, [styles.profileButtonOpen]: openMenu() === "profile" }} aria-label="Profile menu" aria-expanded={openMenu() === "profile"} onClick={() => toggleMenu("profile")}>
						<div class={styles.profile}>
							<div class={styles.profileCopy}>
								<p class={styles.profileName}>{profileName()}</p>
								<p class={styles.profileRole}>{profileRole()}</p>
							</div>
							<span class={styles.profileBadge}>
								<Show when={profileIconUrl()} fallback={profileBadge()}>
									{(iconUrl) => <img src={iconUrl()} alt="" class={styles.profileAvatarImage} />}
								</Show>
							</span>
							<span class={styles.profileChevron} aria-hidden="true">
								<svg viewBox="0 0 20 20">
									<path d="m5 7.5 5 5 5-5" />
								</svg>
							</span>
						</div>
					</button>

					<Show when={openMenu() === "profile"}>
						<div class={styles.dropdown}>
							<div class={styles.dropdownHeader}>
								<div>
									<p class={styles.dropdownEyebrow}>Signed in as</p>
									<strong>{profileName()}</strong>
									<p class={styles.dropdownMeta}>{profileRole()}</p>
								</div>
								<div class={styles.dropdownHeaderActions}>
									<span class={styles.profileMenuBadge}>
										<Show when={profileIconUrl()} fallback={profileBadge()}>
											{(iconUrl) => <img src={iconUrl()} alt="" class={styles.profileAvatarImage} />}
										</Show>
									</span>
									<button type="button" class={styles.mobileDropdownClose} aria-label="Close profile menu" onClick={() => setOpenMenu(null)}>
										<svg viewBox="0 0 20 20" aria-hidden="true">
											<path d="M5 5l10 10M15 5 5 15" />
										</svg>
									</button>
								</div>
							</div>

							<div class={styles.dropdownList}>
								<A href={settingsHref()} class={styles.dropdownItem} onClick={() => setOpenMenu(null)}>
									<span class={`${styles.itemTone} ${styles["tone-blue"]}`} aria-hidden="true" />
									<div class={styles.itemCopy}>
										<strong>Profile</strong>
										<p>Update your learner details and view your profile settings.</p>
									</div>
								</A>

								<A href={settingsHref()} class={styles.dropdownItem} onClick={() => setOpenMenu(null)}>
									<span class={`${styles.itemTone} ${styles["tone-yellow"]}`} aria-hidden="true" />
									<div class={styles.itemCopy}>
										<strong>Settings</strong>
										<p>Manage goals, preferences, reminders, and dashboard options.</p>
									</div>
								</A>

								<button type="button" class={`${styles.dropdownItem} ${styles.dropdownButtonReset}`} onClick={() => void handleLogout()}>
									<span class={`${styles.itemTone} ${styles["tone-teal"]}`} aria-hidden="true" />
									<div class={styles.itemCopy}>
										<strong>Log out</strong>
										<p>End your current session and return to the sign-in screen.</p>
									</div>
								</button>
							</div>
						</div>
					</Show>
				</div>
			</div>
		</header>
	);
};

export default DashboardTopbar;
