/**
 * MobileServerSettings — full-screen stand-in for ServerSettingsModal
 * on mobile. Ported from the new UI: top bar with X / back button +
 * title, a server icon + name hero, then a rounded card listing each
 * category. Tapping a category replaces the body with that tab's
 * panel and swaps the top bar to a back arrow.
 *
 * Rendered as a portal overlay (not the shared Modal) so the surface
 * is true full-screen on mobile. Reuses the existing `OverviewTab`,
 * `RolesTab`, and `EmojisTab` components exported from
 * ServerSettingsModal — same Convex-backed logic as desktop.
 */
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { useQuery } from 'convex/react';
import {
	CaretLeft,
	CaretRight,
	Gear,
	ShieldStar,
	Smiley,
	X,
} from '@phosphor-icons/react';
import { api } from '../../../../../convex/_generated/api';
import {
	EmojisTab,
	OverviewTab,
	type ServerSettingsTab,
} from './ServerSettingsModal';
import { useRolesView } from './RolesView';
import rolesStyles from './RolesView.module.css';
import styles from './MobileServerSettings.module.css';

interface MobileServerSettingsProps {
	isOpen: boolean;
	onClose: () => void;
	initialTab?: ServerSettingsTab;
}

const TABS: Array<{
	id: ServerSettingsTab;
	label: string;
	icon: React.ComponentType<{
		size?: number;
		weight?: 'regular' | 'fill' | 'bold';
	}>;
}> = [
	{ id: 'overview', label: 'Overview', icon: Gear },
	{ id: 'roles', label: 'Roles & Permissions', icon: ShieldStar },
	{ id: 'emojis', label: 'Custom Emoji', icon: Smiley },
];

function getInitials(name: string): string {
	return name
		.split(/\s+/)
		.map((w) => w[0])
		.join('')
		.slice(0, 2)
		.toUpperCase();
}

export function MobileServerSettings({
	isOpen,
	onClose,
	initialTab,
}: MobileServerSettingsProps) {
	// `null` means we're on the category list. A non-null tab id
	// shows that tab's panel full-screen with a back arrow in the
	// top bar.
	const [activeTab, setActiveTab] = useState<ServerSettingsTab | null>(
		initialTab ?? null,
	);

	// Roles & Permissions uses a two-screen flow on mobile: the
	// role list view, then the editor when a role is tapped. The
	// hook owns the selected-id state so desktop and mobile share
	// the same drafts map behind the scenes.
	const rolesView = useRolesView({
		onBack: () => setActiveTab(null),
	});

	useEffect(() => {
		if (isOpen) setActiveTab(initialTab ?? null);
	}, [isOpen, initialTab]);

	// Lock body scroll while the overlay is open.
	useEffect(() => {
		if (!isOpen) return;
		const prev = document.body.style.overflow;
		document.body.style.overflow = 'hidden';
		return () => {
			document.body.style.overflow = prev;
		};
	}, [isOpen]);

	// Escape / top-bar back — pop one level at a time.
	//   roles editor → roles list → category list → close modal
	const popOneLevel = () => {
		if (activeTab === 'roles' && rolesView.selectedId) {
			rolesView.clearSelection();
			return;
		}
		if (activeTab !== null) {
			setActiveTab(null);
			return;
		}
		onClose();
	};

	useEffect(() => {
		if (!isOpen) return;
		const handler = (e: KeyboardEvent) => {
			if (e.key !== 'Escape') return;
			popOneLevel();
		};
		document.addEventListener('keydown', handler);
		return () => document.removeEventListener('keydown', handler);
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isOpen, activeTab, rolesView.selectedId, onClose]);

	const serverSettings = useQuery(api.serverSettings.get, isOpen ? {} : 'skip');

	if (!isOpen) return null;

	const serverName = serverSettings?.serverName || 'Server';
	const serverIcon = serverSettings?.iconUrl || null;

	const activeTabMeta = activeTab
		? TABS.find((t) => t.id === activeTab)
		: undefined;

	const backIsClose = activeTab === null;
	const barTitle = activeTabMeta ? activeTabMeta.label : 'Server Settings';

	return createPortal(
		<div className={styles.overlay} role="dialog" aria-modal="true">
			{/* Top bar — X at the root, back arrow whenever a tab is pushed. */}
			<div className={styles.topBar}>
				<button
					type="button"
					className={styles.topBarButton}
					onClick={popOneLevel}
					aria-label={backIsClose ? 'Close' : 'Back'}
				>
					{backIsClose ? (
						<X size={22} weight="bold" />
					) : (
						<CaretLeft size={22} weight="bold" />
					)}
				</button>
				<div className={styles.topBarTitleBlock}>
					<h2 className={styles.topBarTitle}>{barTitle}</h2>
				</div>
				<div />
			</div>

			{activeTab === null ? (
				<div className={`${styles.body} ${styles.bodyList}`}>
					<div className={styles.hero}>
						{serverIcon ? (
							<img
								src={serverIcon}
								alt={serverName}
								className={styles.heroIcon}
								draggable={false}
							/>
						) : (
							<div className={styles.heroInitials}>
								{getInitials(serverName)}
							</div>
						)}
						<h3 className={styles.heroName}>{serverName}</h3>
					</div>

					<div className={styles.sectionLabel}>Settings</div>
					<div className={styles.tabList}>
						{TABS.map((tab) => {
							const Icon = tab.icon;
							return (
								<button
									key={tab.id}
									type="button"
									className={styles.tabItem}
									onClick={() => setActiveTab(tab.id)}
								>
									<span className={styles.tabItemIcon}>
										<Icon size={18} weight="fill" />
									</span>
									<span>{tab.label}</span>
									<CaretRight
										size={16}
										weight="bold"
										className={styles.tabItemCaret}
									/>
								</button>
							);
						})}
					</div>
				</div>
			) : activeTab === 'roles' ? (
				// Roles & Permissions gets a dedicated two-screen flow:
				//   - no selection → full-screen role list (Create Role +
				//     rows with chevrons)
				//   - role selected → editor content with a "Back to
				//     Roles" row on top for the in-panel pop-back
				<div className={`${styles.body} ${styles.bodyPanel}`}>
					{rolesView.selectedId ? (
						<>
							<div className={rolesStyles.mobileBackRow}>
								<button
									type="button"
									className={rolesStyles.mobileBackButton}
									onClick={rolesView.clearSelection}
								>
									<CaretLeft size={14} weight="bold" />
									Back to Roles
								</button>
							</div>
							{rolesView.header}
							{rolesView.content}
						</>
					) : (
						rolesView.mobileList
					)}
				</div>
			) : (
				<div className={`${styles.body} ${styles.bodyPanel}`}>
					{activeTab === 'overview' && <OverviewTab />}
					{activeTab === 'emojis' && <EmojisTab />}
				</div>
			)}
		</div>,
		document.body,
	);
}
