import { Gear, Plus, SignOut, UserPlus } from '@phosphor-icons/react';
import { useEffect } from 'react';
import { createPortal } from 'react-dom';
import styles from './GuildHeaderDropdown.module.css';

interface GuildHeaderDropdownProps {
	anchorRect: DOMRect;
	onClose: () => void;
	onInviteMembers?: () => void;
	onCreateChannel?: () => void;
	onCreateCategory?: () => void;
	onServerSettings?: () => void;
	onLeaveServer?: () => void;
}

/**
 * Simple portal-based dropdown menu shown below the server header
 * button at the top of the channel sidebar. Escape closes it.
 */
export function GuildHeaderDropdown({
	anchorRect,
	onClose,
	onInviteMembers,
	onCreateChannel,
	onCreateCategory,
	onServerSettings,
	onLeaveServer,
}: GuildHeaderDropdownProps) {
	useEffect(() => {
		const onKey = (e: KeyboardEvent) => {
			if (e.key === 'Escape') onClose();
		};
		document.addEventListener('keydown', onKey);
		return () => document.removeEventListener('keydown', onKey);
	}, [onClose]);

	const top = anchorRect.bottom + 8;
	const left = anchorRect.left;

	const wrap = (handler?: () => void) => () => {
		handler?.();
		onClose();
	};

	return createPortal(
		<div className={styles.overlay} onClick={onClose}>
			<div
				className={styles.menu}
				style={{ position: 'fixed', top, left }}
				onClick={(e) => e.stopPropagation()}
			>
				<button type="button" className={styles.item} onClick={wrap(onInviteMembers)}>
					<span className={styles.itemIcon}>
						<UserPlus size={18} />
					</span>
					<span className={styles.itemLabel}>Invite People</span>
				</button>
				<div className={styles.divider} />
				<button type="button" className={styles.item} onClick={wrap(onCreateChannel)}>
					<span className={styles.itemIcon}>
						<Plus size={18} weight="bold" />
					</span>
					<span className={styles.itemLabel}>Create Channel</span>
				</button>
				<button type="button" className={styles.item} onClick={wrap(onCreateCategory)}>
					<span className={styles.itemIcon}>
						<Plus size={18} weight="bold" />
					</span>
					<span className={styles.itemLabel}>Create Category</span>
				</button>
				<div className={styles.divider} />
				<button type="button" className={styles.item} onClick={wrap(onServerSettings)}>
					<span className={styles.itemIcon}>
						<Gear size={18} />
					</span>
					<span className={styles.itemLabel}>Server Settings</span>
				</button>
				{onLeaveServer && (
					<>
						<div className={styles.divider} />
						<button
							type="button"
							className={`${styles.item} ${styles.itemDanger}`}
							onClick={wrap(onLeaveServer)}
						>
							<span className={styles.itemIcon}>
								<SignOut size={18} />
							</span>
							<span className={styles.itemLabel}>Leave Server</span>
						</button>
					</>
				)}
			</div>
		</div>,
		document.body,
	);
}
