import {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, logout} 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 * as FileSystem from 'expo-file-system';
import applicationApi from "../../api/applicationApi";
import {startActivityAsync} from "expo-intent-launcher";
import {
    openLoadingModal,
    setIndeterminate,
    setLoadingText,
    setProgress
} from "../../features/loadingModal/loadingModalSlice";
import CancelAssemblyModal from "../../components/Modals/CancelAssemblyModal/CancelAssemblyModal";
import {AxiosHeaders} from "axios";
import apiClient from "../../api/apiClient";
import AnimationsView from "../../components/Animations/AnimationsView";
import {ScanningContextProvider} from "../../providers/ScanProvider";
import * as Application from 'expo-application';


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 = Application.nativeApplicationVersion;
        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
                    })
                })
            })
        });
    }


    const configApi = () => {

        apiClient.interceptors.request.use(async (config) => {
            const accessToken = await SecureStore.getItemAsync('accessToken');
            if (!config.headers) {
                config.headers = new AxiosHeaders();
            }
            if (accessToken) {
                config.headers.set('Authorization', `Bearer ${accessToken}`, true);
                config.headers.set('CrptAvailable', 'true', true);
            }
            config.validateStatus = (status) => {
                if (status == 401) {
                    SecureStore.deleteItemAsync('accessToken');
                    dispatch(logout());
                }
                return true;
            };

            return config;
        }, function (error) {
        });
    }

    useEffect(() => {
        configApi();
        checkUpdates();
        loadSettings();
    }, []);

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

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;