import { cn } from "@utils/helpers";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import * as React from "react";
import { useMemo } from "react";
import { useLoggedInUser, useUsers } from "@/contexts/UsersProvider";
import { Peer } from "@/interfaces/Peer";
import ActiveInactiveRow from "@/modules/common-table-rows/ActiveInactiveRow";
import { ExitNodePeerIndicator } from "@/modules/exit-node/ExitNodePeerIndicator";
import { EphemeralPeerIndicator } from "@/modules/peer/EphemeralPeerIndicator";
import { ExpirationDisabledIndicator } from "@/modules/peer/ExpirationDisabledIndicator";
import { usePeerIssueIcon } from "@/modules/peer/PeerIssueIcon";

type Props = {
	peer: Peer;
	linkToPeer?: boolean;
};
export default function PeerNameCell({ peer, linkToPeer = true }: Props) {
	const t = useTranslations("peers");
	const { users } = useUsers();
	const router = useRouter();
	const { isOwnerOrAdmin } = useLoggedInUser();
	const issueIcon = usePeerIssueIcon(peer);

	const userOfPeer = useMemo(() => {
		return users?.find((user) => user.id === peer.user_id);
	}, [users, peer.user_id]);

	const displayUserEmailOrName = userOfPeer?.email || userOfPeer?.name;
	const displayUserId = userOfPeer?.id || peer?.user_id;

	return (
		<div>
			<div
				className={cn(
					"flex items-center max-w-[280px] gap-2 dark:text-neutral-300 text-neutral-500 transition-all py-2 px-3 rounded-md ",
					linkToPeer &&
						"hover:text-neutral-100 hover:bg-nb-gray-900/60 cursor-pointer",
				)}
				data-testid="peer-name-cell"
				aria-label={t("viewDetailsOf", { name: peer.name })}
				onClick={(e) => {
					if (!linkToPeer) return;
					e.preventDefault();
					e.stopPropagation();
					router.push("/peer?id=" + peer.id);
				}}
			>
				<ActiveInactiveRow
					active={peer.connected}
					text={peer.name}
					additionalInfo={
						isOwnerOrAdmin && (
							<>
								<ExitNodePeerIndicator peer={peer} />
								<EphemeralPeerIndicator peer={peer} />
								<ExpirationDisabledIndicator peer={peer} />
							</>
						)
					}
				>
					<div className={"text-nb-gray-400 font-light truncate"}>
						{displayUserEmailOrName ||
							(displayUserId && t("userLabel", { id: displayUserId }))}
					</div>
				</ActiveInactiveRow>
				{isOwnerOrAdmin && (
					<div
						className={
							"ml-auto shrink-0 w-6 h-6 flex items-center justify-center"
						}
					>
						{issueIcon}
					</div>
				)}
			</div>
		</div>
	);
}
