import { Hash } from '@phosphor-icons/react';
import { useVoice } from '../../contexts/VoiceContext';
import { ScreenSharePreview } from './ScreenSharePreview';
import { VoiceGridLayout } from './VoiceGridLayout';
import { VoiceControlBar } from './VoiceControlBar';
import type { VoiceParticipantTileData } from './VoiceParticipantTile';
import styles from './VoiceCallView.module.css';

interface VoiceCallViewProps {
	channelId: string;
}

interface RawParticipant {
	userId: string;
	username?: string;
	avatarUrl?: string;
	isMuted?: boolean;
	isDeafened?: boolean;
	isScreenSharing?: boolean;
	[key: string]: any;
}

export function VoiceCallView({ channelId }: VoiceCallViewProps) {
	const voice = useVoice();

	const rawParticipants: RawParticipant[] =
		(voice?.voiceStates && voice.voiceStates[channelId]) || [];
	const activeSpeakers: Set<string> = voice?.activeSpeakers || new Set();

	const participants: VoiceParticipantTileData[] = rawParticipants.map((p) => ({
		userId: p.userId,
		username: p.username || 'Unknown',
		avatarUrl: p.avatarUrl,
		isMuted: !!p.isMuted,
		isSpeaking: activeSpeakers.has(p.userId),
		isScreenSharing: !!p.isScreenSharing,
	}));

	const channelName = voice?.activeChannelName || 'Voice Channel';

	return (
		<div className={`${styles.root} ${styles.pointerActive}`} data-voice-call-root>
			<div className={styles.voiceHeader}>
				<div className={styles.headerLeftSection}>
					<div className={styles.channelInfoContainer}>
						<Hash size={20} weight="bold" className={styles.channelIcon} />
						<span className={styles.channelName}>{channelName}</span>
					</div>
				</div>
				<div className={styles.headerRightSection} />
			</div>

			<div className={styles.mainContent}>
				<ScreenSharePreview />
				<VoiceGridLayout participants={participants} />
			</div>

			<div className={styles.controlBarContainer}>
				<VoiceControlBar />
			</div>
		</div>
	);
}
