import { FC, useEffect } from 'react';
import { View } from 'react-native';
import { NavigationProp, useNavigation, CommonActions } from '@react-navigation/native';
import { Formik } from 'formik';
import * as yup from 'yup';

import { Header, Input, Button, BigText, PageWrapper } from '../../components';

import { ButtonVariants } from '../../types/components';
import { StoreType, storage } from '../../storage';
import { NAVIGATION_PAGES } from '../../types';

import { useLoginMutation } from '@api/auth';
import { fetchAndSaveStatistics } from 'src/database/statisticsService';

type Props = {
  navigation: NavigationProp<any>;
};

const LoginSchema = yup.object({
  login: yup.string().required(),
  pass: yup.string().required()
});

const LoginScreen: FC<Props> = ({ navigation }) => {
  const { dispatch } = useNavigation();
  const isFirstLaunch = storage.get('isFirstLaunch', StoreType.BOOLEAN) ?? true;

  const { data, mutate: userLogin } = useLoginMutation();

  const updateLocalData = async (token: string) => {
    await fetchAndSaveStatistics(token);
  };

  useEffect(() => {
    if (data && data.token) {
      storage.set('token', data.token);
      storage.set('uid', data.uid.toString());
      storage.set('isFirstLaunch', false);
      updateLocalData(data.token);

      isFirstLaunch
        ? dispatch(
            CommonActions.reset({
              index: 1,
              routes: [{ name: NAVIGATION_PAGES.INFO }]
            })
          )
        : dispatch(
            CommonActions.reset({
              index: 1,
              routes: [{ name: NAVIGATION_PAGES.IN_APP }]
            })
          );
    }
  }, [data]);

  return (
    <PageWrapper>
      <Header label={'Login'} />
      <Formik
        initialValues={{
          login: '',
          pass: ''
        }}
        onSubmit={({ login, pass }) => {
          userLogin({
            login,
            pass
          });
        }}
        validationSchema={LoginSchema}
      >
        {(props) => (
          <>
            <View style={{ gap: 15 }}>
              <BigText>Welcome back</BigText>
              <Input
                header={'Email address'}
                placeholder={'Email or login'}
                inputMode={'email'}
                onChange={props.handleChange('login')}
                value={props.values.login}
                onBlur={props.handleBlur('login')}
                formikError={
                  data?.result_description || (props.touched.login && props.errors.login)
                }
              />
              <Input
                header={'Password'}
                isPrivate={true}
                placeholder={'Login'}
                onChange={props.handleChange('pass')}
                value={props.values.pass}
                onBlur={props.handleBlur('pass')}
                formikError={data?.result_description || (props.touched.pass && props.errors.pass)}
              />
            </View>
            <View style={{ gap: 30, marginTop: '5%' }}>
              <Button
                variant={ButtonVariants.TEXT}
                onPress={() => navigation.navigate(NAVIGATION_PAGES.RESET_PASSWORD)}
              >
                Forgot password
              </Button>
              <Button onPress={props.handleSubmit}>Login</Button>
            </View>
          </>
        )}
      </Formik>
    </PageWrapper>
  );
};

export default LoginScreen;
