/**
 * MobileSetStatusSheet — bottom sheet opened by tapping your own
 * avatar on the MobileYouPage (or the status row below the name).
 * Lets you flip between Online / Idle / Do Not Disturb / Invisible.
 *
 * Writes flow through `api.auth.updateStatus({ userId, status })`.
 * The Convex query at `api.auth.getPublicKeys` is reactive, so all
 * subscribers update automatically once the mutation completes.
 */
import { useState } from 'react';
import { useMutation, useQuery } from 'convex/react';
import { Check, X } from '@phosphor-icons/react';
import { BottomSheet } from '@discord-clone/ui';
import { api } from '../../../../../convex/_generated/api';
import type { Id } from '../../../../../convex/_generated/dataModel';
import styles from './MobileSetStatusSheet.module.css';

export type UiPresence = 'online' | 'idle' | 'dnd' | 'invisible';

interface MobileSetStatusSheetProps {
	isOpen: boolean;
	onClose: () => void;
}

interface StatusOption {
	id: UiPresence;
	label: string;
	subtitle?: string;
	dotClass: string;
}

const STATUS_OPTIONS: StatusOption[] = [
	{
		id: 'online',
		label: 'Online',
		dotClass: styles.statusDotOnline,
	},
	{
		id: 'idle',
		label: 'Idle',
		dotClass: styles.statusDotIdle,
	},
	{
		id: 'dnd',
		label: 'Do Not Disturb',
		subtitle: "You won't receive notifications on desktop",
		dotClass: styles.statusDotDnd,
	},
	{
		id: 'invisible',
		label: 'Invisible',
		subtitle: "You'll appear offline",
		dotClass: styles.statusDotOffline,
	},
];

export function MobileSetStatusSheet({ isOpen, onClose }: MobileSetStatusSheetProps) {
	const userId = typeof localStorage !== 'undefined' ? localStorage.getItem('userId') : null;
	const allUsers = useQuery(api.auth.getPublicKeys) ?? [];
	const me = allUsers.find((u) => u.id === userId);
	const current = (me?.status ?? 'online') as UiPresence;
	const updateStatus = useMutation(api.auth.updateStatus);
	const [busy, setBusy] = useState<UiPresence | null>(null);

	const handleSelect = async (next: UiPresence) => {
		if (busy || !userId) return;
		if (next === current) {
			onClose();
			return;
		}
		setBusy(next);
		try {
			await updateStatus({ userId: userId as Id<'userProfiles'>, status: next });
			onClose();
		} catch (err) {
			console.warn('Failed to set presence:', err);
		} finally {
			setBusy(null);
		}
	};

	return (
		<BottomSheet isOpen={isOpen} onClose={onClose} disableDefaultHeader showHandle>
			<div className={styles.root}>
				<div className={styles.topBar}>
					<div />
					<h2 className={styles.topBarTitle}>Set Status</h2>
					<button
						type="button"
						className={styles.topBarButton}
						onClick={onClose}
						aria-label="Close"
					>
						<X size={20} weight="bold" />
					</button>
				</div>

				<div className={styles.sectionLabel}>Online Status</div>

				<div className={styles.statusList}>
					{STATUS_OPTIONS.map((option) => {
						const selected = option.id === current;
						return (
							<button
								key={option.id}
								type="button"
								className={styles.statusItem}
								onClick={() => handleSelect(option.id)}
								disabled={busy !== null}
							>
								<span className={`${styles.statusDot} ${option.dotClass}`} />
								<span className={styles.statusText}>
									<span className={styles.statusName}>{option.label}</span>
									{option.subtitle && (
										<span className={styles.statusSubtitle}>{option.subtitle}</span>
									)}
								</span>
								<span
									className={`${styles.statusCheck} ${selected ? '' : styles.statusCheckHidden}`}
								>
									<Check size={13} weight="bold" />
								</span>
							</button>
						);
					})}
				</div>
			</div>
		</BottomSheet>
	);
}
