import { useEffect, useRef, useState } from 'react';
import { DownloadSimple, X } from '@phosphor-icons/react';
import { usePlatform } from '../../platform';
import styles from './UpdateBanner.module.css';

const RELEASE_URL =
	'https://gitea.moyettes.com/Moyettes/DiscordClone/releases/tag/latest';

interface UpdateInfo {
	updateAvailable: boolean;
	updateType?: 'major' | 'minor' | 'patch';
	latestVersion?: string;
	currentVersion?: string;
	apkUrl?: string;
}

export function UpdateBanner() {
	const platform = usePlatform() as any;
	const [info, setInfo] = useState<UpdateInfo | null>(null);
	const [dismissed, setDismissed] = useState(false);
	const [installing, setInstalling] = useState(false);
	const [progress, setProgress] = useState<number | null>(null);
	const checkedRef = useRef(false);

	useEffect(() => {
		if (checkedRef.current) return;
		checkedRef.current = true;
		if (!platform?.features?.hasNativeUpdates) return;
		const checkUpdate = platform?.updates?.checkUpdate;
		if (typeof checkUpdate !== 'function') return;

		let cancelled = false;
		(async () => {
			try {
				const result = await checkUpdate();
				if (cancelled) return;
				if (result?.updateAvailable) setInfo(result);
			} catch (e) {
				console.warn('[UpdateBanner] checkUpdate failed', e);
			}
		})();
		return () => {
			cancelled = true;
		};
	}, [platform]);

	useEffect(() => {
		if (!installing) return;
		const listen = platform?.updates?.onDownloadProgress;
		if (typeof listen !== 'function') return;
		try {
			listen((evt: { progress?: number } | number) => {
				const raw = typeof evt === 'number' ? evt : evt?.progress;
				if (typeof raw === 'number') {
					const pct = raw > 1 ? raw : raw * 100;
					setProgress(Math.max(0, Math.min(100, pct)));
				}
			});
		} catch (e) {
			console.warn('[UpdateBanner] onDownloadProgress failed', e);
		}
	}, [installing, platform]);

	if (!platform?.features?.hasNativeUpdates) return null;
	if (!info?.updateAvailable || dismissed) return null;

	const handleInstall = async () => {
		const install = platform?.updates?.installUpdate;
		if (typeof install === 'function') {
			try {
				setInstalling(true);
				setProgress(0);
				await install();
				return;
			} catch (e) {
				console.warn('[UpdateBanner] installUpdate failed, falling back', e);
				setInstalling(false);
				setProgress(null);
			}
		}
		platform?.links?.openExternal?.(RELEASE_URL);
	};

	const versionLabel = info.latestVersion
		? `v${info.latestVersion}`
		: 'latest release';
	const currentLabel = info.currentVersion ? ` (you have v${info.currentVersion})` : '';

	return (
		<div
			className={`${styles.banner} ${installing ? styles.progressRow : ''}`}
			role="status"
		>
			<div className={styles.iconWrap}>
				<DownloadSimple size={20} weight="bold" />
			</div>
			<div className={styles.body}>
				<span className={styles.title}>Update available</span>
				<span className={styles.subtitle}>
					{installing
						? `Downloading ${versionLabel}…${
								progress !== null ? ` ${Math.round(progress)}%` : ''
							}`
						: `${versionLabel}${currentLabel}`}
				</span>
			</div>
			<div className={styles.actions}>
				<button
					type="button"
					className={styles.primaryBtn}
					onClick={handleInstall}
					disabled={installing}
				>
					{installing ? 'Installing…' : 'Update now'}
				</button>
				{!installing && (
					<button
						type="button"
						className={styles.dismissBtn}
						onClick={() => setDismissed(true)}
						aria-label="Dismiss update banner"
					>
						<X size={16} weight="bold" />
					</button>
				)}
			</div>
			{installing && progress !== null && (
				<div className={styles.progressTrack}>
					<div
						className={styles.progressFill}
						style={{ width: `${progress}%` }}
					/>
				</div>
			)}
		</div>
	);
}

export default UpdateBanner;
