import {View} from 'react-native';
import {Center, Heading, Spinner, HStack} from '@gluestack-ui/themed';
import {animated, useSpring} from '@react-spring/native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {useSelector} from 'react-redux';
import {RootState, store} from '@redux/store';
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';
import {initKey} from '@helper/storage/bdm/encryption';
import DBSchemas from '@helper/storage/bdm/schemas';
import {convertDatabaseChat} from '@configs/chat/types';
import {addChatEntity} from '@components/chat/initChatDatabase';
import {initDatabase} from '@helper/storage/bdm/init';

const AnimationView = animated(View);

export async function onAppStart() {
  await initAppData();

  await initKey();

  BigDataManager.initDatabase()
    .then(async () => {
      const keys = BigDataManager.databases.chatRoomInfos.keys;
      const entries =
        (await BigDataManager.databases.chatRoomInfos.getAllEntries()) || [];

      entries.sort((a, b) =>
        a[keys.timestamp] > b[keys.timestamp]
          ? 1
          : b[keys.timestamp] > a[keys.timestamp]
          ? -1
          : 0,
      );

      for (let i = 0; i < entries.length; i++) {
        console.log(entries[i]);
        const chat = convertDatabaseChat(entries[i]);
        if (chat === undefined) continue;

        await initDatabase(DBSchemas.chat, chat.roomId);

        addChatEntity(chat);

        /*if (chat.roomId === 'test') {
          const chatDBKeys = BigDataManager.databases.chat.keys;
          for (let i = 0; i < 10; i++) {
            await BigDataManager.databases.chat.setEntry(
              {
                [chatDBKeys.UserId]: MyUserManager.getSelectedUserId(),
                [chatDBKeys.data]: 'heyho',
              },
              chat.roomId,
            );
          }
        }*/
      }

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

      store.dispatch(appNonSaveVarActions.setAppStatus(appStatus.APP_RUNNING));
    })
    .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 currentTheme = useSelector(
    (state: RootState) => state.nonSaveVariables.theme.colors,
  );

  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(() => {
    (async () => {
      await onAppStart();
    })();
  }, []);

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

  return (
    <SafeAreaView
      style={[{flex: 1, backgroundColor: currentTheme.backgroundDark400}]}>
      <Center height={'100%'}>
        <AnimationView
          style={{
            height: 100,
            position: 'absolute',
            backgroundColor: currentTheme.secondary400,
            borderRadius: 8,
            width: motionProps.width,
            opacity: motionProps.opacity,
            transform: [{translateX: motionProps.translateX}, {translateY: 5}],
          }}
        />
        <Heading style={{color: '#fff'}}>{lang.appName}</Heading>

        <HStack marginTop={5} justifyContent="center">
          <Spinner color={currentTheme.secondary400} size="large" />
        </HStack>
      </Center>
    </SafeAreaView>
  );
}

export default StartHelper;
