/**
 * FileSizeLimitModal — shown when a user drops (or picks) a file that
 * exceeds the homeserver's advertised maximum upload size. Clicking
 * Cancel closes the modal; there's no "upload anyway" path because
 * the homeserver will just reject the POST with a 413 regardless.
 *
 * The numbers we show come from `MediaManager.getMaxUploadSize`
 * (which calls `GET /_matrix/media/v3/config` on the user's own
 * homeserver). This is a per-homeserver-federation policy — different
 * homeservers have different limits — so the copy reflects that.
 */
import { Modal, Button } from '@brycord/ui';
import { WarningCircle } from '@phosphor-icons/react';
import styles from './FileSizeLimitModal.module.css';

interface FileSizeLimitModalProps {
	isOpen: boolean;
	onClose: () => void;
	/** The file(s) that tripped the limit — for display only. */
	fileName: string;
	/** Actual file size in bytes. */
	actualBytes: number;
	/** Homeserver-advertised maximum in bytes. */
	limitBytes: number;
}

function formatBytes(bytes: number): string {
	if (!Number.isFinite(bytes)) return 'unlimited';
	if (bytes < 1024) return `${bytes} B`;
	if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
	if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
	return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

export function FileSizeLimitModal({
	isOpen,
	onClose,
	fileName,
	actualBytes,
	limitBytes,
}: FileSizeLimitModalProps) {
	if (!isOpen) return null;

	return (
		<Modal.Root isOpen={isOpen} onClose={onClose} size="small">
			<Modal.Header title="File size limit exceeded" onClose={onClose} />
			<Modal.Content className={styles.content}>
				<div className={styles.iconRow}>
					<div className={styles.iconBadge}>
						<WarningCircle size={28} weight="fill" />
					</div>
				</div>
				<p className={styles.body}>
					The file <strong>{fileName}</strong> is{' '}
					<strong>{formatBytes(actualBytes)}</strong>, which exceeds the
					maximum upload size allowed by this homeserver of{' '}
					<strong>{formatBytes(limitBytes)}</strong>.
				</p>
				<p className={styles.hint}>
					Try a smaller file, compress the file, or upload it to another
					service and share the link instead.
				</p>
			</Modal.Content>
			<Modal.Footer>
				<Button variant="primary" onClick={onClose}>
					Cancel
				</Button>
			</Modal.Footer>
		</Modal.Root>
	);
}
