import React, { useCallback, useEffect, useState } from 'react';
import { View, ScrollView, Text } 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';
import { usePostGetProfileInfoDataQuery } from '@api/user';
import { Colors } from 'src/theme';
import { getFontSize } from 'src/utils';

const SignUpSchema = yup.object({
  first_name: yup.string().required(),
  last_name: yup.string().required(),
  date_of_birth: yup.string().required(),
  homebase: yup.number().required().min(1, 'Region of origin is 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 { data: profileData } = usePostGetProfileInfoDataQuery(
    data?.token || '',
    data?.uid ? +data.uid : 0,
    data?.token ? true : false
  );
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);

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

      fetchData();
    }, [])
  );

  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);

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

  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={async (values) => {
                setIsSubmitting(true);

                const dateObject = new Date(values.date_of_birth);
                const formattedDate = dateObject.toISOString().split('T')[0];

                const data = {
                  user: {
                    ...user,
                    first_name: values.first_name,
                    last_name: values.last_name,
                    date_of_birth: formattedDate,
                    homebase: values.homebase,
                    homebase2: values.homebase2 ?? -1
                  },
                  photo: values.photo.uri
                    ? {
                        type: values.photo.type,
                        uri: values.photo.uri,
                        name: values.photo.uri.split('/').pop()!
                      }
                    : {
                        type: undefined,
                        uri: undefined,
                        name: undefined
                      }
                };

                await userRegister(data, {
                  onSuccess: (data) => {
                    if (data && data.token) {
                      storage.set('token', data.token);
                      storage.set('uid', data.uid.toString());
                      updateLocalData(data.token);
                    } else {
                      setIsSubmitting(false);
                    }
                  },
                  onError: () => {
                    setIsSubmitting(false);
                  }
                });
              }}
            >
              {(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)}
                  />
                  {props.touched.homebase && props.errors.homebase ? (
                    <Text
                      style={{
                        color: Colors.RED,
                        fontSize: getFontSize(12),
                        fontFamily: 'redhat-600',
                        marginTop: 5
                      }}
                    >
                      {props.errors.homebase}
                    </Text>
                  ) : null}
                  <ModalFlatList
                    headerTitle={'Second region'}
                    selectedObject={(data) => props.setFieldValue('homebase2', data.id)}
                  />
                  <View style={{ marginTop: 10 }}>
                    <Button onPress={props.handleSubmit} disabled={isSubmitting}>
                      Sign up
                    </Button>
                  </View>
                </View>
              )}
            </Formik>
          </KeyboardAwareScrollView>
        </View>
      </ScrollView>
    </PageWrapper>
  );
};

export default EditAccount;
