import React, { FC, useState } from 'react';
import { Text, View } from 'react-native';
import { Formik } from 'formik';
import * as yup from 'yup';

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

import { styles } from './styles';
import { useResetPasswordMutation } from '@api/auth';
import { useNavigation } from '@react-navigation/native';

const ResetPasswordSchema = yup.object({
  email: yup.string().email().required()
});

const ResetPasswordScreen: FC = () => {
  const { data, error, mutate: resetPassword } = useResetPasswordMutation();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const navigation = useNavigation();

  return (
    <PageWrapper>
      <Header label={'Reset Password'} />
      <Formik
        initialValues={{
          email: ''
        }}
        onSubmit={({ email }) => {
          resetPassword(
            {
              email
            },
            { onSuccess: (res) => res.result === 'OK' && setIsModalVisible(true) }
          );
        }}
        validationSchema={ResetPasswordSchema}
      >
        {(props) => (
          <>
            <View style={{ gap: 15 }}>
              <BigText>Please enter your valid email</BigText>
              <Text style={styles.smallText}>
                Type email which you used for registration and check your inbox for further
                instructions
              </Text>
              <Input
                header={'Email address'}
                placeholder={'Email'}
                inputMode={'email'}
                onChange={props.handleChange('email')}
                value={props.values.email}
                onBlur={props.handleBlur('email')}
                formikError={
                  data?.result_description || (props.touched.email && props.errors.email)
                }
              />
            </View>
            <View style={{ marginTop: '10%' }}>
              <Button onPress={props.handleSubmit}>Send</Button>
            </View>
          </>
        )}
      </Formik>
      <WarningModal
        isVisible={isModalVisible}
        onClose={() => {
          setIsModalVisible(false);
          navigation.goBack();
        }}
        type={'success'}
        message={
          'Password reset link has been sent to your email. Please check your inbox for further instructions.'
        }
        title="Success!"
      />
    </PageWrapper>
  );
};

export default ResetPasswordScreen;
