import { useQuery } from 'convex/react';
import { Tooltip } from '@discord-clone/ui';
import { ChatCircleDots } from '@phosphor-icons/react';
import { useLocation, useNavigate } from 'react-router-dom';
import { api } from '../../../../../convex/_generated/api';
import { useIsMobile } from '../../hooks/useIsMobile';
import styles from './GuildList.module.css';

interface GuildListProps {
	onCreateServer?: () => void;
}

/**
 * Discord Clone is a single-server app, so the GuildList shows:
 *   - Home (DMs) button
 *   - A single "server" icon sourced from `serverSettings`
 * The new UI's multi-server affordances (add-server, drag-to-reorder) are
 * hidden until the Convex schema supports multiple servers.
 */
export function GuildList(_props: GuildListProps) {
	const navigate = useNavigate();
	const location = useLocation();
	const isMobile = useIsMobile();
	const segments = location.pathname.split('/').filter(Boolean);
	const topLevel = segments[0] === 'channels' ? segments[1] : undefined;
	const serverSettings = useQuery(api.serverSettings.get);
	const channels = useQuery(api.channels.list);

	const isHomeSelected = topLevel === '@me' || !topLevel;
	const isServerSelected = !!topLevel && topLevel !== '@me' && topLevel !== 'you';

	const handleHomeClick = () => navigate('/channels/@me');

	const handleServerClick = () => {
		// On mobile, land on the channel list view first so the user
		// sees what's in the server before being dropped into a chat.
		// On desktop we auto-open the first text channel because the
		// full 3-column layout already shows the channel list beside
		// the chat so it's not a jarring jump.
		if (isMobile) {
			navigate('/channels/home');
			return;
		}
		const firstText = channels?.find((c) => c.type === 'text');
		if (firstText) navigate(`/channels/home/${firstText._id}`);
		else navigate('/channels/home');
	};

	const serverName = serverSettings?.serverName || 'Server';
	const serverIconUrl: string | null = serverSettings?.iconUrl || null;
	const initials = serverName
		.split(/\s+/)
		.map((w) => w[0])
		.join('')
		.slice(0, 2)
		.toUpperCase();

	return (
		<div className={styles.list}>
			<div className={styles.guildItem}>
				<GuildIndicator active={isHomeSelected} />
				<Tooltip content="Direct Messages" placement="right">
					<button
						className={`${styles.guildIcon} ${styles.homeIcon} ${isHomeSelected ? styles.selected : ''}`}
						onClick={handleHomeClick}
					>
						<ChatCircleDots size={28} weight="fill" />
					</button>
				</Tooltip>
			</div>

			<div className={styles.divider} />

			<div className={styles.guildItem}>
				<GuildIndicator active={isServerSelected} />
				<Tooltip content={serverName} placement="right">
					<div
						className={`${styles.guildIcon} ${isServerSelected ? styles.selected : ''}`}
						role="button"
						tabIndex={0}
						onClick={handleServerClick}
						onKeyDown={(e) => {
							if (e.key === 'Enter' || e.key === ' ') {
								e.preventDefault();
								handleServerClick();
							}
						}}
					>
						{serverIconUrl ? (
							<img src={serverIconUrl} alt={serverName} className={styles.guildImage} />
						) : (
							<span className={styles.guildInitials}>{initials}</span>
						)}
					</div>
				</Tooltip>
			</div>

			{/* Add-a-server button removed — this build is a single-server
			    deployment so there's nothing to add. Drop the trailing
			    divider + Plus tile entirely. */}
		</div>
	);
}

function GuildIndicator({ active }: { active: boolean }) {
	return (
		<div className={styles.guildIndicator}>
			<span
				className={styles.guildIndicatorBar}
				style={{
					height: active ? '40px' : '0px',
					transition: 'height 0.15s ease',
				}}
			/>
		</div>
	);
}
