import React, { useCallback, useEffect, useState } from 'react';
import { View, ScrollView } from 'react-native';
import { Formik } from 'formik';
import * as yup from 'yup';
import { CommonActions, useFocusEffect, useNavigation } from '@react-navigation/native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';

import { AvatarPicker, BigText, Button, Header, Input, PageWrapper } from '../../../components';
import { InputDatePicker } from '../../../components/Calendar/InputDatePicker';
import { ModalFlatList } from '../../../components/FlatList/modal-flatlist';
import { useRegisterMutation } from '@api/auth';
import { storage } from '../../../storage';

import store from '../../../storage/zustand';
import { NAVIGATION_PAGES } from '../../../types';
import { fetchAndSaveStatistics } from 'src/database/statisticsService';

const SignUpSchema = yup.object({
  first_name: yup.string().required(),
  last_name: yup.string().required(),
  date_of_birth: yup.string().required(),
  homebase: yup.number().required(),
  homebase2: yup.number().optional()
});

//TODO: formik avatar | date and flatlist error shown

const EditAccount = () => {
  const { dispatch } = useNavigation();

  const [user] = store((state) => [state.registration.user]);

  const { data, error, mutate: userRegister } = useRegisterMutation();
  const [isLoading, setIsLoading] = useState(true);

  useFocusEffect(
    useCallback(() => {
      const fetchData = async () => {
        setIsLoading(false);
      };

      fetchData();
    }, [])
  );

  useEffect(() => {
    if (data && data.token) {
      storage.set('token', data.token);
      storage.set('uid', data.uid.toString());
      updateLocalData(data.token);
      dispatch(
        CommonActions.reset({
          index: 1,
          routes: [{ name: NAVIGATION_PAGES.IN_APP }]
        })
      );
    }
  }, [data]);

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

  if (isLoading) {
    return null;
  }

  return (
    <PageWrapper>
      <ScrollView showsVerticalScrollIndicator={false}>
        <View style={{ gap: 10 }}>
          <Header label={'Sign Up'} />
          <BigText>Edit account data</BigText>
          <KeyboardAwareScrollView>
            <Formik
              initialValues={{
                photo: {
                  type: '',
                  uri: '',
                  name: ''
                },
                first_name: '',
                last_name: '',
                date_of_birth: '',
                homebase: 0,
                homebase2: undefined
              }}
              validationSchema={SignUpSchema}
              onSubmit={(values) => {
                const data = {
                  user: {
                    ...user,
                    first_name: values.first_name,
                    last_name: values.last_name,
                    date_of_birth: values.date_of_birth,
                    homebase: values.homebase,
                    homebase2: values.homebase2
                  },
                  photo: {
                    type: values.photo.type,
                    uri: values.photo.uri,
                    name: values.photo.uri.split('/').pop()!
                  }
                };

                userRegister(data);
              }}
            >
              {(props) => (
                <View>
                  <View style={{ display: 'flex', alignItems: 'center' }}>
                    <AvatarPicker selectedAvatar={(asset) => props.setFieldValue('photo', asset)} />
                  </View>
                  <Input
                    onChange={props.handleChange('first_name')}
                    value={props.values.first_name}
                    onBlur={props.handleBlur('first_name')}
                    placeholder={'Enter your first name'}
                    header={'First name'}
                    formikError={props.touched.first_name && props.errors.first_name}
                  />
                  <Input
                    onChange={props.handleChange('last_name')}
                    value={props.values.last_name}
                    onBlur={props.handleBlur('last_name')}
                    placeholder={'Enter your last name'}
                    header={'Last name'}
                    formikError={props.touched.last_name && props.errors.last_name}
                  />
                  <InputDatePicker
                    headerTitle={'Date of birth'}
                    selectedDate={(date) => props.setFieldValue('date_of_birth', date)}
                    formikError={props.touched.date_of_birth && props.errors.date_of_birth}
                  />
                  <ModalFlatList
                    headerTitle={'Region of origin'}
                    selectedObject={(data) => props.setFieldValue('homebase', data.id)}
                  />
                  <ModalFlatList
                    headerTitle={'Second region'}
                    selectedObject={(data) => props.setFieldValue('homebase2', data.id)}
                  />
                  <View style={{ marginTop: 10 }}>
                    <Button onPress={props.handleSubmit}>Sign up</Button>
                  </View>
                </View>
              )}
            </Formik>
          </KeyboardAwareScrollView>
        </View>
      </ScrollView>
    </PageWrapper>
  );
};

export default EditAccount;
