/**
 * ReactionsModal — full breakdown of every reaction on a single
 * message. Matches the Discord "Reactions" popup: an emoji chip
 * column on the left, the user list for the selected emoji on the
 * right. Clicking the X next to your own row removes that reaction;
 * other users' rows render the close affordance as `null` so the
 * column only lets you manage your own state.
 */
import { useState } from 'react';
import { X } from '@phosphor-icons/react';
import { Avatar, Modal } from '@discord-clone/ui';
import type { ReactionUser } from './Messages';
import { TwemojiImg } from './TwemojiImg';
import { resolveReactionKeyToUnicode } from '../../utils/emojiLookup';
import styles from './ReactionsModal.module.css';

export interface ReactionsModalReaction {
	emoji: string;
	count: number;
	me: boolean;
	users: ReactionUser[];
}

interface ReactionsModalProps {
	isOpen: boolean;
	onClose: () => void;
	reactions: ReactionsModalReaction[];
	myUserId: string | null;
	customEmojiByName: Map<string, string>;
	/**
	 * Called when the viewer clicks the X next to their own row — the
	 * parent is responsible for wiring `api.reactions.remove`. The
	 * modal trusts the parent and optimistically just closes if this
	 * was the viewer's last remaining reaction.
	 */
	onRemoveOwnReaction: (emoji: string) => void;
}

export function ReactionsModal({
	isOpen,
	onClose,
	reactions,
	myUserId,
	customEmojiByName,
	onRemoveOwnReaction,
}: ReactionsModalProps) {
	// Which emoji tab is active — defaults to the first reaction.
	// Resets whenever the set of reactions changes (e.g. after removal).
	const [activeEmoji, setActiveEmoji] = useState<string | null>(null);
	const effectiveEmoji =
		activeEmoji && reactions.some((r) => r.emoji === activeEmoji)
			? activeEmoji
			: reactions[0]?.emoji ?? null;

	const activeReaction = reactions.find((r) => r.emoji === effectiveEmoji);

	const renderEmojiGlyph = (emojiKey: string) => {
		const customUrl = /^[a-zA-Z0-9_]+$/.test(emojiKey)
			? customEmojiByName.get(emojiKey.toLowerCase())
			: undefined;
		if (customUrl) {
			return (
				<img
					src={customUrl}
					alt={`:${emojiKey}:`}
					className={styles.emojiChipImage}
					draggable={false}
				/>
			);
		}
		return (
			<TwemojiImg
				emoji={resolveReactionKeyToUnicode(emojiKey)}
				size={20}
			/>
		);
	};

	return (
		<Modal.Root isOpen={isOpen} onClose={onClose} size="medium">
			<Modal.Header title="Reactions" onClose={onClose} />
			<Modal.Content>
				<div className={styles.body}>
					<div className={styles.emojiColumn}>
						{reactions.map((r) => {
							const isActive = effectiveEmoji === r.emoji;
							return (
								<button
									key={r.emoji}
									type="button"
									className={`${styles.emojiChip} ${isActive ? styles.emojiChipActive : ''}`}
									onClick={() => setActiveEmoji(r.emoji)}
								>
									{renderEmojiGlyph(r.emoji)}
									<span className={styles.emojiCount}>{r.count}</span>
								</button>
							);
						})}
					</div>
					<div className={styles.usersColumn}>
						{activeReaction?.users.map((u) => {
							const isMe = myUserId !== null && u.userId === myUserId;
							return (
								<div key={u.userId} className={styles.userRow}>
									<div className={styles.userAvatar}>
										<Avatar
											src={undefined}
											fallback={u.displayName || u.username}
											size={32}
										/>
									</div>
									<div className={styles.userMeta}>
										<span className={styles.userDisplayName}>
											{u.displayName || u.username}
										</span>
										<span className={styles.userTag}>{u.username}</span>
									</div>
									{isMe && (
										<button
											type="button"
											className={styles.removeButton}
											onClick={() =>
												onRemoveOwnReaction(activeReaction.emoji)
											}
											aria-label="Remove your reaction"
											title="Remove your reaction"
										>
											<X size={14} weight="bold" />
										</button>
									)}
								</div>
							);
						})}
					</div>
				</div>
			</Modal.Content>
		</Modal.Root>
	);
}
