import React, { FC, useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Linking } from 'react-native';
import { NavigationProp } from '@react-navigation/native';
import { Formik } from 'formik';
import * as yup from 'yup';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';

import {
  PageWrapper,
  Header,
  Button,
  BigText,
  CheckBox,
  Input,
  WarningModal
} from '../../../components';
import { NAVIGATION_PAGES } from '../../../types';
import { useJoinTestMutation } from '@api/auth';
import store from '../../../storage/zustand';
import { styles } from './styles';
import { useNetInfo } from '@react-native-community/netinfo';

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

const JoinSchema = yup.object({
  username: yup.string().required('username is required').min(4),
  email: yup.string().required('email is required').email('enter valid email'),
  password: yup.string().required('password is required').min(8),
  repeatPassword: yup
    .string()
    .required('repeat your password')
    .oneOf([yup.ref('password'), 'repeat password'], 'passwords must match'),
  checkboxAgreed: yup.bool().isTrue()
});

const JoinUsScreen: FC<Props> = ({ navigation }) => {
  const { data, mutateAsync: JoinTest } = useJoinTestMutation();
  const [isWarningModalVisible, setIsWarningModalVisible] = useState(false);
  const netInfo = useNetInfo();

  const updateRegistrationUserData = store((state) => state.registration.updateRegistrationUserData);

  return (
    <PageWrapper>
      <ScrollView showsVerticalScrollIndicator={false}>
        <Header label={'Sign Up'} />
        <View style={{ gap: 15 }}>
          <BigText>Join us. It's free!</BigText>
          <KeyboardAwareScrollView>
            <Formik
              initialValues={{
                email: '',
                username: '',
                password: '',
                repeatPassword: '',
                checkboxAgreed: false
              }}
              validationSchema={JoinSchema}
              onSubmit={(values) => {
                const { email, username, password } = values;
                if (!netInfo?.isInternetReachable && !netInfo?.isConnected) {
                  setIsWarningModalVisible(true);
                  return;
                }

                JoinTest({
                  email,
                  username
                }).then((data) => {
                  if (!data?.field && data?.result === 'OK') {
                    navigation.navigate(NAVIGATION_PAGES.REGISTER_ACCOUNT_DATA);

                    updateRegistrationUserData({ email, username, password });
                  }
                });
              }}
            >
              {(props) => (
                <View style={{ gap: 15 }}>
                  <Input
                    onChange={props.handleChange('username')}
                    value={props.values.username}
                    onBlur={props.handleBlur('username')}
                    placeholder={'Enter your username'}
                    header={'Username'}
                    formikError={
                      data?.field === 'USERNAME USED'
                        ? data?.field
                        : props.touched.username && props.errors.username
                    }
                  />
                  <Input
                    onChange={props.handleChange('email')}
                    value={props.values.email}
                    onBlur={props.handleBlur('email')}
                    placeholder={'Enter your email'}
                    header={'Email address'}
                    inputMode={'email'}
                    formikError={
                      data?.field === 'EMAIL USED'
                        ? data?.field
                        : props.touched.email && props.errors.email
                    }
                  />
                  <Input
                    onChange={props.handleChange('password')}
                    value={props.values.password}
                    onBlur={props.handleBlur('password')}
                    placeholder={'Enter your password'}
                    header={'Password'}
                    isPrivate={true}
                    formikError={props.touched.password && props.errors.password}
                  />
                  <Input
                    onChange={props.handleChange('repeatPassword')}
                    value={props.values.repeatPassword}
                    onBlur={props.handleBlur('repeatPassword')}
                    placeholder={'Repeat your password'}
                    header={'Confirm password'}
                    isPrivate={true}
                    formikError={props.touched.repeatPassword && props.errors.repeatPassword}
                  />
                  <TouchableOpacity
                    onPress={() =>
                      props.setFieldValue('checkboxAgreed', !props.values.checkboxAgreed)
                    }
                    style={styles.checkbox}
                  >
                    <CheckBox
                      onChange={(value) => props.setFieldValue('checkboxAgreed', value)}
                      value={props.values.checkboxAgreed}
                    />
                    <Text style={styles.text}>
                      I accept{' '}
                      <Text
                        onPress={() => Linking.openURL('https://nomadmania.com/terms/')}
                        style={styles.checkboxLink}
                      >
                        NM Terms & Conditions
                      </Text>
                    </Text>
                  </TouchableOpacity>
                  <Text style={styles.textError}>
                    {props.touched.checkboxAgreed && props.errors.checkboxAgreed
                      ? 'To use our service you need to agree'
                      : null}
                  </Text>
                  <Button onPress={props.handleSubmit}>Continue</Button>
                </View>
              )}
            </Formik>
          </KeyboardAwareScrollView>
        </View>
      </ScrollView>
      <WarningModal
        isVisible={isWarningModalVisible}
        onClose={() => setIsWarningModalVisible(false)}
        type="offline"
      />
    </PageWrapper>
  );
};

export default JoinUsScreen;
