import {Platform, StyleSheet, View, ScrollView} from 'react-native';

import {Center, Heading, Text, Spinner, HStack} from '@gluestack-ui/themed';
import {animated, useSpring} from '@react-spring/native';

import {SafeAreaView} from 'react-native-safe-area-context';

import {useSelector, useDispatch} from 'react-redux';
import {RootState, store} from '@redux/store';

//import {getBackgroundColor} from '@configs/colors';
import {useEffect} from 'react';
import {initAppData} from '@helper/appData';
import {appStatus} from '@configs/appNonSaveVar';
import {appNonSaveVarActions} from '@configs/appNonSaveVarReducer';
import BigDataManager from '@helper/storage/BigDataManager';

const AnimationView = animated(View);

function onAppStart() {
  initAppData().then(() => {
    BigDataManager.initDatabase()
      .then(() => {
        console.log('finish');
        setTimeout(() => {
          store.dispatch(
            appNonSaveVarActions.setAppStatus(appStatus.APP_RUNNING),
          );
        }, 250);
      })
      .catch(err => {
        console.error("Database Error! Can't start App :(");
      });

    //store.dispatch(actions.loadPreferences(appVar));
  });
}

function StartHelper() {
  const currentAppStatus = useSelector(
    (state: RootState) => state.nonSaveVariables.appStatus,
  );

  const lang = useSelector((state: RootState) => state.appVariables.lang);
  const theme = useSelector(
    (state: RootState) => state.appVariables.preferences.theme,
  );

  const [motionProps, api] = useSpring(
    () => ({
      from: {
        translateX: -150,
        width: 4,
        opacity: 1,
      },
    }),
    [],
  );

  useEffect(() => {
    api.start({
      to: [
        {
          translateX: 150,
          width: 4,
          opacity: 1,
        },
        {
          translateX: -150,
          width: 4,
          opacity: 1,
        },
      ],
      loop: true,
    });
  }, []);

  useEffect(onAppStart, []);

  if (currentAppStatus === appStatus.APP_RUNNING) return null;

  return (
    <SafeAreaView style={[{flex: 1, backgroundColor: '#333'}]}>
      <Center height={'100%'}>
        <AnimationView
          style={{
            height: 100,
            position: 'absolute',

            backgroundColor: '#f22',
            borderRadius: 8,

            width: motionProps.width,
            opacity: motionProps.opacity,
            transform: [{translateX: motionProps.translateX}, {translateY: 5}],
          }}
        />
        <Heading>{lang.appName}</Heading>

        <HStack marginTop={5} justifyContent="center">
          <Spinner color="#ff7d4f" accessibilityLabel="Loading posts" />
          <Heading color="#ff7d4f" size="md">
            {lang.startHelper1}
          </Heading>
        </HStack>
      </Center>
    </SafeAreaView>
  );
}

export default StartHelper;
