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

import {Center, Heading, Text, Spinner, HStack} from 'native-base';
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 '@caj/redux/store';

import imgSrc from '@caj/img/maimg.png';
import {placeholder} from '@caj/lang/default';
import {getBackgroundColor} from '@caj/configs/colors';
import {useEffect} from 'react';
import {initAppData} from '@caj/helper/appData';
import {appStatus} from '@caj/configs/appNonSaveVar';
import {appNonSaveVarActions} from '@caj/configs/appNonSaveVarReducer';
import BigDataManager from '@caj/helper/storage/BigDataManager';
import {initKey} from '@caj/helper/storage/bdm/encryption';
import UserManager from '@caj/user/UserManager';
import MyUserManager from '@caj/user/MyUserManager';
import DBSchemas from '@caj/helper/storage/bdm/schemas';
import {chatTags, chatType} from '@caj/components/chat/types';

const AnimationView = animated(View);

function onAppStart() {
  initAppData().then(async () => {
    await initKey();

    BigDataManager.initDatabase()
      .then(async () => {
        console.log('finish');
        await BigDataManager.databases.users.setEntry({
          UserId: 'test',
          AccountName: '#845613',
          Username: 'TestGroupVirtual',
          Description: 'This is a test account that is not real. ^^',
          FollowersCount: 2,
          FollowingCount: 24,
          lastUpdateTimestamp: 412341234,
          ProfilePicture: '',
          ProfilePictureBinaryHQ: new ArrayBuffer(0),
          ProfilePictureBinaryLQ: new ArrayBuffer(0),
          XpLevel: 0,
          XpPoints: 0,
        });

        store.dispatch(
          appNonSaveVarActions.setAppStatus(appStatus.APP_RUNNING),
        );

        store.dispatch(
          appNonSaveVarActions.setChatEntity({
            id: MyUserManager.getSelectedUserId(),
            type: chatType.User,
            tags: [chatTags.GOOD_FRIEND],
            unreadMessages: 1234,
          }),
        );
        store.dispatch(
          appNonSaveVarActions.setChatEntity({
            id: 'test',
            type: chatType.User,
            tags: [chatTags.GROUP, chatTags.GOOD_FRIEND, chatTags.FRIEND],
            unreadMessages: 0,
          }),
        );
      })
      .catch(err => {
        console.error("Database Error! Can't start App :(", err);
      });

    //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: getBackgroundColor(theme)}]}>
      <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 mt="5" space={2} justifyContent="center">
          <Spinner color="#ff7d4f" accessibilityLabel="Loading posts" />
          <Heading color="#ff7d4f" fontSize="md">
            {lang.startHelper1}
          </Heading>
        </HStack>
      </Center>
    </SafeAreaView>
  );
}

export default StartHelper;
