import Constants from 'expo-constants';
import * as Linking from 'expo-linking';
import { Alert, Platform, BackHandler } from 'react-native';
// import * as Updates from 'expo-updates';

export function checkVersion(fetchedVersion: { version: string; isActive: boolean }) {
    const currentVersion = Constants.expoConfig?.version;

    if (!fetchedVersion.isActive) {
        Alert.alert(
            '伺服器維護中，敬請見諒',
            '',
            [
                {
                    text: '確認',
                    onPress: () => {
                        if (Platform.OS === 'android') {
                            BackHandler.exitApp();
                        } else {
                            return;
                        }
                    }
                }
            ],
            { cancelable: false }
        );
        // Prevent any further code execution
        throw new Error('MAINTENANCE_MODE');
    }

    function compareVersions(v1: string, v2: string): boolean {
        const v1Parts = v1.split('.').map(Number);
        const v2Parts = v2.split('.').map(Number);

        for (let i = 0; i < v1Parts.length; i++) {
            if (v1Parts[i] < v2Parts[i]) return true;
            if (v1Parts[i] > v2Parts[i]) return false;
        }
        return false;
    }

    // if (currentVersion && currentVersion < fetchedVersion.version) {
    if (currentVersion && compareVersions(currentVersion, fetchedVersion.version)) {
        Alert.alert(
            '請更新到最新版本',
            'Please update to the latest version of the app to continue.',
            [
                {
                    text: '現在更新',
                    onPress: () => {
                        const url =
                            Platform.OS === 'ios'
                                ? 'https://apps.apple.com/hk/app/crazycharge-pro/id6748374363'
                                : 'https://play.google.com/store/apps/details?id=hk.ayf.crazycharge';
                        Linking.openURL(url);
                    }
                },
                { text: '取消', style: 'cancel' }
            ],
            { cancelable: false }
        );
    }
}
