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') && (
                <ForcedUpdateModal latestVersion={state.latestVersion} />
            )}
        </UpdateContext.Provider>
    );
}

function ForcedUpdateModal({ latestVersion }) {
    const { links } = usePlatform();
    const handleDownload = () => {
        links.openExternal(RELEASE_URL);
    };

    return (
        <div className="forced-update-overlay">
            <div className="forced-update-modal">
                <h2>Update Required</h2>
                <p>
                    A new version (v{latestVersion}) is available. This update is required to continue using the app.
                </p>
                <button className="forced-update-btn" onClick={handleDownload}>
                    Download Update
                </button>
            </div>
        </div>
    );
}

export function TitleBarUpdateIcon() {
    const { links } = usePlatform();
    const update = useUpdateCheck();

    if (!update) return null;

    const handleClick = () => {
        links.openExternal(RELEASE_URL);
    };

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