import {SafeAreaView, StyleSheet, View} from "react-native";
import LoginScreen from "../LoginScreen/LoginScreen";
import MainScreen from "../MainScreen/MainScreen";
import SearchBar from "../../components/SearchBar/SearchBar";
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 {closeScanModal, setScannedData} from "../../features/scanModal/scanModalSlice";
import LoadingModal from "../../components/Modals/LoadingModal/LoadingModal";

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

    const dispatch = useDispatch();

    const loadSettings = async () => {
        const token = await SecureStore.getItemAsync('accessToken');
        if (!token) return;
        dispatch(login({accessToken: token}));
    }

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

    return (

        <View style={styles.main}>
            {isAuthorized ? <MainScreen/> : <LoginScreen/>}
            <View style={[styles.overlay, {display: dim ? 'flex' : 'none'}]}/>
            <LoadingModal/>
            <ScanModal/>
            <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;