import React, { useState, useEffect, createContext, useContext } from 'react';
import { usePlatform } from '../platform';
import ColoredIcon from './ColoredIcon';
import updateIcon from '../assets/icons/update.svg';

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

const UpdateContext = createContext(null);

export function useUpdateCheck() {
    return useContext(UpdateContext);
}

export function UpdateProvider({ children }) {
    const { updates, features } = usePlatform();
    const [state, setState] = useState(null);

    useEffect(() => {
        if (!features.hasNativeUpdates || !updates) return;

        updates.checkUpdate().then((result) => {
            if (!result?.updateAvailable) return;
            setState(result);
        }).catch(() => {});
    }, []);

    return (
        <UpdateContext.Provider value={state}>
            {children}
            {state && (state.updateType === 'major' || state.updateType === 'minor' || !features.hasWindowControls) && (
                <ForcedUpdateModal updateType={state.updateType} latestVersion={state.latestVersion} />
            )}
        </UpdateContext.Provider>
    );
}

function ForcedUpdateModal({ updateType, latestVersion }) {
    const { links, updates } = usePlatform();
    const [downloading, setDownloading] = useState(false);
    const [progress, setProgress] = useState(0);
    const [error, setError] = useState(null);

    useEffect(() => {
        if (!downloading || !updates?.onDownloadProgress) return;
        updates.onDownloadProgress(({ percent }) => {
            setProgress(percent);
        });
    }, [downloading]);

    const handleDownload = async () => {
        if (updates?.installUpdate) {
            setDownloading(true);
            setError(null);
            try {
                await updates.installUpdate();
            } catch (e) {
                setError('Download failed. Please try again.');
                setDownloading(false);
            }
        } else {
            links.openExternal(RELEASE_URL);
        }
    };

    const isPatch = updateType === 'patch';

    return (
        <div className="forced-update-overlay">
            <div className="forced-update-modal">
                <h2>{isPatch ? 'Update Available' : 'Update Required'}</h2>
                <p>
                    {isPatch
                        ? `A new version (v${latestVersion}) is available.`
                        : `A new version (v${latestVersion}) is available. This update is required to continue using the app.`
                    }
                </p>
                {downloading ? (
                    <div className="update-progress">
                        <div className="update-progress-bar-bg">
                            <div
                                className="update-progress-bar-fill"
                                style={{ width: `${progress}%` }}
                            />
                        </div>
                        <span className="update-progress-text">Downloading... {progress}%</span>
                    </div>
                ) : (
                    <button className="forced-update-btn" onClick={handleDownload}>
                        Download Update
                    </button>
                )}
                {error && <p className="update-error-text">{error}</p>}
            </div>
        </div>
    );
}

export function TitleBarUpdateIcon() {
    const { links, updates } = usePlatform();
    const update = useUpdateCheck();
    const [downloading, setDownloading] = useState(false);
    const [progress, setProgress] = useState(0);

    useEffect(() => {
        if (!downloading || !updates?.onDownloadProgress) return;
        updates.onDownloadProgress(({ percent }) => {
            setProgress(percent);
        });
    }, [downloading]);

    if (!update) return null;

    const handleClick = async () => {
        if (updates?.installUpdate && !downloading) {
            setDownloading(true);
            try {
                await updates.installUpdate();
            } catch {
                setDownloading(false);
            }
        } else if (!downloading) {
            links.openExternal(RELEASE_URL);
        }
    };

    const label = downloading
        ? `Downloading update... ${progress}%`
        : `Update available: v${update.latestVersion}`;

    return (
        <button
            className="titlebar-btn"
            onClick={handleClick}
            aria-label={label}
            title={label}
            style={{ borderRight: '1px solid var(--app-frame-border)' }}
        >
                            <div style={{ marginRight: '12px' }}>
                                <ColoredIcon src={updateIcon} color="#3ba55c" size="20px" />
                            </div>
        </button>
    );
}
