import { useQuery } from 'convex/react';
import { api } from '../../../../../convex/_generated/api';
import styles from './TypingUsers.module.css';

interface TypingUsersProps {
	channelId: string;
}

export function TypingUsers({ channelId }: TypingUsersProps) {
	const userId = typeof localStorage !== 'undefined' ? localStorage.getItem('userId') : null;
	const typing = useQuery(
		api.typing.getTyping,
		channelId ? { channelId: channelId as any } : 'skip',
	);
	const users = useQuery(api.auth.getPublicKeys) ?? [];

	const others = (typing ?? []).filter((t: any) => t.userId !== userId);
	if (others.length === 0) return null;

	const names = others
		.map((t: any) => {
			const u = users.find((x) => x.id === t.userId);
			return u?.displayName || u?.username || 'Someone';
		})
		.slice(0, 3);

	const text =
		names.length === 1
			? `${names[0]} is typing…`
			: names.length === 2
				? `${names[0]} and ${names[1]} are typing…`
				: 'Several people are typing…';

	return (
		<div className={styles.container}>
			<span className={styles.dots}>
				<span className={styles.dot} />
				<span className={styles.dot} />
				<span className={styles.dot} />
			</span>
			<span className={styles.text}>{text}</span>
		</div>
	);
}
