import React, { useState, useEffect } from 'react';
import { useRoute } from '@react-navigation/native';
import { Platform, View, TextInput, Text, StyleSheet, TouchableOpacity, ScrollView, Image } from 'react-native';
import { connect } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../../reducers/contextProvider';
import { customeButtons, customStyles, GetPageTheme } from "../../styles/Global";
import Container from '../../components/container';
import { MaterialCommunityIcons } from '../../components/icons';
import GradientButton from '../../components/gradientButton';
import { notify } from '../../components/notify';
import { METHODS, getMethodName } from '../../constants/methodNames';
import { getforgotpasswordotp } from '../../controller/functions';
import CustomLoader from '../../components/CustomLoader';
import { get_item } from '../../components/localStorage';


function ForgotPassword(props) {
  const route = useRoute();
  const PageTheme = GetPageTheme(props.DarkTheme, route.name);
  const customeButton = customeButtons(props.DarkMode, route.name);
  const customStyle = customStyles(props.DarkMode, route.name);


  const [state, setState] = useState({username:''});
  const [processing, setProcessing] = useState(false);

  const handlegetOTP = () => {
    const { username } = state;
    if (!username.trim()) {
      notify('Please enter username', 'SHORT');
      return;
    }
    Send_OTP();
  }

  const Send_OTP = async () => {
    const { username } = state;
    setProcessing(true);

    let projectInfo = await get_item('projectInfo');
    let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};
    let baseurl = projectDetails.baseURL || '';

    const method_name = getMethodName(METHODS.OTP_SEND);
    const url = baseurl + method_name;
    const data = { un: username };
    console.log(url, data)
    await getforgotpasswordotp(url, data)
      .then(async (res) => {
        setProcessing(false);
        console.log(res, "response...")
        if (res?.Status == false) {
          notify(res?.Text,'SHORT') // invalid username
        } else if (res?.Status == true) {
          notify("OTP send successfully.",'SHORT')
          props?.navigation?.navigate('VerifyOTP', {username : username});
          setState({username:''})
        } else if (res.networkErr && res.error) {
          notify('Please connect to internet-' + res.error, 'SHORT');
        } else if (!res.false && res.error) {
          notify(res.error, 'SHORT');
        }

      })
      .catch((err) => {
        setProcessing(false);
        console.log('onPage otp send error1', err);
      });

  }

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS === 'ios'}>
    {processing && <CustomLoader title="Sending OTP..." />}
    <Image style={styles.performicsLogo} source={require('../../assets/image/PerformicsLogo.png')} />

    <View style={styles.infoTextContainer}>
    <Text style={styles.fyourpass}>Forgot your password</Text>
      <Text style={styles.infoText}>Please enter your username. We'll send an OTP to the phone number associated with your account.</Text>
     </View>

     <View style={[customStyle.formGroup,customStyle.mt50]}>
      <TextInput 
        style={[customStyle.inputStyle,customStyle.pl40]}              
        placeholder="Username"         
        autoComplete='off'   
        placeholderTextColor={PageTheme.$placeholder_color} 
        value={state.username}
        onChangeText={(val)=>setState({...state,username:val})}
        onSubmitEditing={() => handlegetOTP()}
      />
      <MaterialCommunityIcons style={customStyle.formInputLeftIcon} size={18} name='account-outline' color={PageTheme.$placeholder_color} />
     </View>

     <View style={[customStyle.footerView]}>
       <GradientButton {...props} title={'Get OTP'} onPress={()=>{handlegetOTP()}}/>
     </View>

     <TouchableOpacity onPress={()=> props.navigation.reset({ index: 0, routes: [{ name: 'Login' }] })}>
     <Text style={styles.backtologin}>Back to Login</Text>
     </TouchableOpacity>
    </Container>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ForgotPassword);

const styles = StyleSheet.create({
 performicsLogo : {
  width:"60%",
  height:"15%",
  resizeMode:'contain',
  marginTop:40
 },
 backtologin:{
  color:'#2196F3',fontSize:17, marginTop:20
 },
 fyourpass: {
  color:'#000000', fontSize: 22,
  fontWeight: '400',
  paddingHorizontal: 30,
  
 },
 infoTextContainer: {
  alignItems: 'flex-start',
  alignSelf: 'flex-start',
  alignContent: 'flex-start'
},
infoText: {
  paddingHorizontal: 30,
  marginTop: 20,
  fontSize: 16
}
});
