import { useNavigate } from "@solidjs/router";
import { For, type JSX } from "solid-js";
import { User } from "../../../lib/icons";
import { useAppShellData } from "../../app-shell/data/app-shell.context";
import { getWorkspaceSurfaceRoute } from "../../app-shell/data/workspace-routes";
import { profileMenuSections } from "../../app-shell/data/shell.data";
import styles from "./ProfileMenu.module.scss";

type ProfileMenuProps = {
	id: string;
	menuRef?: (element: HTMLDivElement) => void;
	onSelect: () => void;
	variant?: "popover" | "workspace";
};

export const ProfileMenu = (props: ProfileMenuProps): JSX.Element => {
	const variant = props.variant ?? "popover";
	const appShellData = useAppShellData();
	const navigate = useNavigate();
	const activeUserProfile = () => appShellData.activeUserProfile();

	const handleSelect = (actionId: string): void => {
		if (actionId === "account-settings" || actionId === "security" || actionId === "theme-preferences") {
			navigate(getWorkspaceSurfaceRoute("settings"));
		}

		props.onSelect();
	};

	return (
		<div
			id={props.id}
			classList={{
				[styles.menu]: true,
				[styles.menuWorkspace]: variant === "workspace",
			}}
			role="menu"
			aria-label="Profile menu"
			ref={props.menuRef}
			data-ui="profile-menu"
			data-variant={variant}
		>
			<div class={styles.summary} data-slot="profile-summary">
				<div class={styles.avatar} aria-hidden="true">
					<span class={styles.avatarRing} />
					<span class={styles.avatarCore}>
						<User size={16} strokeWidth={2} />
					</span>
				</div>

				<div class={styles.summaryCopy}>
					<strong class={styles.name}>{activeUserProfile().name}</strong>
					<span class={styles.email}>{activeUserProfile().email}</span>
					<span class={styles.role}>{activeUserProfile().roleLabel}</span>
					<span class={styles.context}>{activeUserProfile().contextLabel}</span>
				</div>
			</div>

			<div class={styles.sections} data-slot="profile-sections">
				<For each={profileMenuSections}>
					{(section): JSX.Element => (
						<div class={styles.section} data-slot="profile-section" data-section-id={section.id}>
							<For each={section.items}>
								{(item): JSX.Element => {
									const Icon = item.icon;

									return (
										<button
											type="button"
											role="menuitem"
										classList={{
											[styles.item]: true,
											[styles.itemDanger]: item.tone === "danger",
										}}
									data-slot="profile-action"
									data-action-id={item.id}
									data-tone={item.tone ?? "default"}
									onClick={() => handleSelect(item.id)}
									>
											<span class={styles.itemIcon} aria-hidden="true">
												<Icon size={16} strokeWidth={2} />
											</span>
											<span class={styles.itemLabel}>{item.label}</span>
										</button>
									);
								}}
							</For>
						</div>
					)}
				</For>
			</div>
		</div>
	);
};
