import React, {useRef} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  TextInput,
  ScrollView,
} from 'react-native';
import {
  Container,
  Icon,
  ModalOTP,
  ModalError,
  Button,
} from 'components';
import {Colors} from 'global-styles';
import styles from './styles';
import {useKeyboard} from 'utilities';
import useLogin from './useLogin';
import {useTranslation} from 'react-i18next';
import { RFValue } from 'react-native-responsive-fontsize';
import { userLogin } from 'services';
import { useDispatch} from 'react-redux';
import {signIn} from 'actions';
import AsyncStorage from '@react-native-async-storage/async-storage';
 
const Login = ({route, navigation}, props) => {
  const {t, i18n} = useTranslation();
  const keyboardHeight = useKeyboard();
  const passwordInputRef = useRef();
  const dispatch = useDispatch();
  const {
    email,
    setEmail,
    password,
    setPassword,
    isPasswordVisible,
    setIsPasswordVisible,
    modalOTP,
    otpCode,
    setOTPCode,
    loading,
    error,
    modal,
    setModal,
  } = useLogin(navigation);

  const onLogin = async () => {
    const payload = {
      email: email.toLowerCase(),
      password: password,
    };

    const res = await userLogin(payload);
    console.log(res);
    if (res._error) {
      console.log(res._error);
    } else {
      await AsyncStorage.setItem('token', res._data.user_token.access_token);
      dispatch(signIn({
          token: res._data.user_token,
          user: res._data.user,
      }));
    }
  };

  return (
    <Container backgroundColor={Colors.WHITE} safeAreaStyleProps={styles.container}>
          {/* <TouchableOpacity
            onPress={() => setModalLanguage(true)}
            style={styles.translateButton}>
            <Icon
              name="translate"
              type="MaterialCommunityIcons"
              style={styles.translateButtonIcon}
            />
            <Image
              source={
                i18n.language === 'id'
                  ? require('assets/images/indonesia-flag.png')
                  : require('assets/images/english-flag.png')
              }
              style={styles.translateButtonImage}
            />
          </TouchableOpacity> */}
          <ScrollView
            keyboardShouldPersistTaps='always'
          >
          <View style={styles.boardingSection}>
            {/* <Image
              source={require('assets/images/login_1.png')}
              style={styles.boardingImage}
            /> */}
            <View style={styles.boardingContentSection}>
              <Text style={styles.boardingTitle}>Naise</Text>
            </View>
          </View>
          <View style={styles.wrapper}>
            <View style={styles.formSection}>
              <Text style={styles.formLabel}>
                Email
              </Text>
              <View style={styles.postSection}>
                <View style={styles.inputSection}>
                  <TextInput
                    style={styles.input}
                    value={email}
                    onChangeText={val => setEmail(val)}
                    placeholder="email@gmail.com"
                    returnKeyType='next'
                    onSubmitEditing={() => passwordInputRef.current.focus()}
                  />
                </View>
              </View>
              {error?.phone?.message && (
                <Text style={styles.error}>{error.phone.message}</Text>
              )}
              <Text style={[styles.formLabel, { marginTop: RFValue(20)}]}>
                Password
              </Text>
              <View style={styles.postSection}>
                <View style={styles.inputSection}>
                  <TextInput
                    style={styles.input}
                    ref={passwordInputRef}
                    value={password}
                    secureTextEntry={!isPasswordVisible}
                    onChangeText={val => setPassword(val)}
                    placeholder="Password"
                  />
                </View>
                <TouchableOpacity
                  onPress={() => setIsPasswordVisible(!isPasswordVisible)}
                >
                  <Icon 
                    name={!isPasswordVisible ?  "eye" : "eye-with-line"}
                    type="Entypo"
                    style={{ color: Colors.DARK_GREY, fontSize: RFValue(20) }}
                  />
                </TouchableOpacity>
              </View>
              {error?.phone?.message && (
                <Text style={styles.error}>{error.phone.message}</Text>
              )}
            </View>
            <View style={styles.buttonSignInSection}>
              <Button
                title={t('login')}
                onPress={() => onLogin()}
                disabled={loading ? true : email === '' ? true : false}
                loading={loading}
              />
            </View>
          </View>
          </ScrollView>
      <ModalOTP
        isVisible={modalOTP.visible}
        code={otpCode}
        setCode={setOTPCode}
        loading={modalOTP.loading}
        error={error?.otp}
        onSubmit={() => alert('token verified')}
      />
      <ModalError
        isVisible={modal.visible}
        message={modal.message}
        onClose={() => setModal({visible: false, message: ''})}
      />
    </Container>
  );
};

export default Login;
