import { useQuery } from 'convex/react';
import { MagnifyingGlass } from '@phosphor-icons/react';
import { useNavigate, useParams } from 'react-router-dom';
import { api } from '../../../../../convex/_generated/api';
import { DMListItem } from './DMListItem';
import styles from './DMLayout.module.css';

export function DMLayout() {
	const navigate = useNavigate();
	const params = useParams<{ channelId?: string }>();
	const userId = typeof localStorage !== 'undefined' ? localStorage.getItem('userId') : null;
	const dms = useQuery(api.dms.listDMs, userId ? { userId: userId as any } : 'skip') ?? [];

	return (
		<div className={styles.container}>
			<div className={styles.header}>
				<span className={styles.headerTitle}>Messages</span>
				<div className={styles.headerActions}>
					<button type="button" className={styles.iconButton} aria-label="Search">
						<MagnifyingGlass size={18} weight="regular" />
					</button>
					{/* Add Friends button is removed — this build auto-friends
					    every user on the server, so there's nothing the button
					    could do besides open a no-op sheet. */}
				</div>
			</div>
			<div className={styles.list}>
				{dms.length === 0 ? (
					<div className={styles.empty}>No direct messages yet</div>
				) : (
					dms.map((dm) => (
						<DMListItem
							key={dm.channel_id}
							dm={dm}
							selected={params.channelId === dm.channel_id}
							onClick={() => navigate(`/channels/@me/${dm.channel_id}`)}
						/>
					))
				)}
			</div>
		</div>
	);
}
