import {Linking, StyleSheet, View} from "react-native";
import LoginScreen from "../LoginScreen/LoginScreen";
import MainScreen from "../MainScreen/MainScreen";
import React, {useEffect} from "react";
import {background} from "../../css/colors";
import {useDispatch, useSelector} from "react-redux";
import {RootState} from "../../redux/store";
import {login} from "../../features/auth/authSlice";
import * as SecureStore from 'expo-secure-store';
import Toast from "react-native-toast-message";
import toastConfig from "../../components/Toast/Toast";
import ScanModal from "../../components/SearchBar/ScanModal";
import LoadingModal from "../../components/Modals/LoadingModal/LoadingModal";
import ReprintModal from "../../components/Modals/ReprintModal/ReprintModal";
import assemblyApi from "../../api/assemblyApi";
import {setAssembly, setLocalState, setOrder} from "../../features/assembly/assemblySlice";
import ordersApi from "../../api/ordersApi";
import ImageZoomModal from "../../components/Modals/ImageZoomModal/ImageZoomModal";
import SortingModal from "../../components/Modals/SortingModal/SortingModal";
import {ASSEMBLY_STATE} from "../../types/assembly";
import Constants from "expo-constants";
import * as FileSystem from 'expo-file-system';
import applicationApi from "../../api/applicationApi";
import {ActivityAction, startActivityAsync} from "expo-intent-launcher";
import {RenderTargetOptions} from "@shopify/flash-list";
import KeyEvent from 'react-native-keyevent';
import {
    openLoadingModal,
    setIndeterminate,
    setLoadingText,
    setProgress
} from "../../features/loadingModal/loadingModalSlice";

function CommonPage() {
    const dim = useSelector((state: RootState) => state.interface.dim);
    const isAuthorized = useSelector((state: RootState) => state.auth.isAuthorized);

    const dispatch = useDispatch();
    const loadSettings = async (): Promise<boolean> => {
        const token = await SecureStore.getItemAsync('accessToken');
        if (!token) return false;
        dispatch(login({accessToken: token}));
        return true;
    }
    const loadAssembly = async () => {
        assemblyApi.hasActive().then(({has}) => {
            if (!has) return;
            assemblyApi.getActive().then(assembly => {
                ordersApi.getOrderById(assembly.orderId).then(order => {
                    dispatch(setAssembly(assembly));
                    dispatch(setOrder(order));
                    dispatch(setLocalState(assembly.state as ASSEMBLY_STATE));
                })
            })
        })
    }
    const initialize = () => {
        loadSettings().then(isSettingsLoaded => {
            if (!isSettingsLoaded) return;
            loadAssembly();
        })
    }


    const checkUpdates = async () => {
        const currentVersion = Constants.manifest2?.extra?.expoClient?.version || Constants.manifest?.version;

        applicationApi.getVersion('assemblr').then(({latest_version}) => {

            if (currentVersion == latest_version) return;
            dispatch(setIndeterminate(false));
            dispatch(setLoadingText("Загрузка обновления..."));
            dispatch(setProgress(0));
            dispatch(openLoadingModal());
            const apkPath = FileSystem.documentDirectory + "update.apk";
            applicationApi.download(apkPath, 'assemblr', latest_version, data => {
                dispatch(setProgress(data.totalBytesWritten / data.totalBytesExpectedToWrite));
            }).then(() => {
                FileSystem.getContentUriAsync(apkPath).then(localUri => {
                    startActivityAsync('android.intent.action.INSTALL_PACKAGE', {
                        data: localUri,
                        flags: 1
                    })
                })
            })
        });
    }
    useEffect(() => {
        checkUpdates();
    }, []);

    return (
        <View style={styles.main}>
            {isAuthorized ? <MainScreen/> : <LoginScreen/>}
            <View style={[styles.overlay, {display: dim ? 'flex' : 'none'}]}/>
            <LoadingModal/>
            <ScanModal/>
            <ReprintModal/>
            <ImageZoomModal/>
            <SortingModal/>
            <Toast config={toastConfig}/>
        </View>

    )
}

const styles = StyleSheet.create({
    main: {
        display: "flex",
        flexDirection: "column",
        flexGrow: 1,
        flex: 1,
        backgroundColor: background
    },
    overlay: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 2,
    }
});

export default CommonPage;