import { FC, useEffect, useState } 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, WarningModal } 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';
import { useNetInfo } from '@react-native-community/netinfo';
import { usePostGetProfileInfoDataQuery } from '@api/user';
import { useMessagesStore } from 'src/stores/unreadMessagesStore';
import { useFriendsNotificationsStore } from 'src/stores/friendsNotificationsStore';

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 updateNotificationStatus = useFriendsNotificationsStore(
    (state) => state.updateNotificationStatus
  );
  const updateUnreadMessagesCount = useMessagesStore((state) => state.updateUnreadMessagesCount);

  const { data: profileData } = usePostGetProfileInfoDataQuery(
    data?.token || '',
    data?.uid ? +data.uid : 0,
    data?.token ? true : false
  );
  const [isSubmitting, setIsSubmitting] = useState(false);

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

  const [isWarningModalVisible, setIsWarningModalVisible] = useState(false);
  const netInfo = useNetInfo();

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

  useEffect(() => {
    if (profileData) {
      const userInfo = {
        avatar: profileData?.data?.user_data.avatar ?? '',
        first_name: profileData?.data?.user_data.first_name,
        last_name: profileData?.data?.user_data.last_name,
        homebase_flag: profileData?.data?.user_data.flag1
      };
      storage.set('currentUserData', JSON.stringify(userInfo));
      setIsSubmitting(false);

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

  return (
    <PageWrapper>
      <Header label={'Login'} />
      <Formik
        initialValues={{
          login: '',
          pass: ''
        }}
        onSubmit={async ({ login, pass }) => {
          setIsSubmitting(true);
          if (netInfo?.isInternetReachable || netInfo?.isConnected) {
            await userLogin(
              {
                login,
                pass
              },
              {
                onSuccess: (res) => {
                  if (res && !res?.token) {
                    setIsSubmitting(false);
                  }
                },
                onError: () => {
                  setIsSubmitting(false);
                }
              }
            );
          } else {
            setIsWarningModalVisible(true);
          }
        }}
        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={'Password'}
                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} disabled={isSubmitting}>
                Login
              </Button>
            </View>
          </>
        )}
      </Formik>
      <WarningModal
        isVisible={isWarningModalVisible}
        onClose={() => setIsWarningModalVisible(false)}
        type="offline"
      />
    </PageWrapper>
  );
};

export default LoginScreen;
