import SelectionStore from '@app/stores/SelectionStore';
import ServerStore from '@app/stores/ServerStore';
import { SpaceManager } from '@brycord/matrix-client';
import { Modal } from '@brycord/ui';
/**
 * LeaveServerModal — confirmation dialog for the "Leave Server"
 * action in the GuildHeaderDropdown. Calls `SpaceManager.leaveServer`
 * on confirm, which walks every linked channel and leaves them all
 * before leaving the space itself. On success, navigates home and
 * optimistically removes the server from ServerStore so the sidebar
 * updates instantly without waiting for the sync echo.
 */
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './LeaveServerModal.module.css';

interface LeaveServerModalProps {
	isOpen: boolean;
	onClose: () => void;
	serverId: string;
	serverName: string;
}

export function LeaveServerModal({ isOpen, onClose, serverId, serverName }: LeaveServerModalProps) {
	const navigate = useNavigate();
	const [busy, setBusy] = useState(false);
	const [error, setError] = useState<string | null>(null);

	const handleConfirm = async () => {
		if (busy) return;
		setBusy(true);
		setError(null);
		try {
			await SpaceManager.getInstance().leaveServer(serverId);
			// Optimistic local cleanup — the sync echo will also
			// remove the server but the sidebar shouldn't wait for
			// it. Clearing the selection prevents the app from
			// rendering a now-stale channel view.
			ServerStore.handleServerDelete(serverId);
			SelectionStore.selectServer(null);
			onClose();
			navigate('/channels/@me');
		} catch (err: any) {
			setError(err?.message || 'Failed to leave server.');
			setBusy(false);
		}
	};

	return (
		<Modal.Root isOpen={isOpen} onClose={busy ? () => {} : onClose} size="small">
			<Modal.Header title="Leave Server" onClose={busy ? () => {} : onClose} />
			<Modal.Content>
				<div className={styles.body}>
					<p className={styles.description}>
						Are you sure you want to leave <strong>{serverName}</strong>? You'll need a new invite to rejoin, and you'll
						leave every channel in this server.
					</p>

					{error && <div className={styles.error}>{error}</div>}

					<div className={styles.actions}>
						<button type="button" className={styles.secondaryButton} onClick={onClose} disabled={busy}>
							Cancel
						</button>
						<button type="button" className={styles.dangerButton} onClick={handleConfirm} disabled={busy}>
							{busy ? 'Leaving…' : 'Leave Server'}
						</button>
					</div>
				</div>
			</Modal.Content>
		</Modal.Root>
	);
}
