import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  Platform,
  TouchableWithoutFeedback,
  Keyboard,
  KeyboardAvoidingView,
  ScrollView,
  DeviceEventEmitter,
} from 'react-native';
import R from '../../../assets/R';
import HeaderBack from '../../../components/Header/HeaderBack';
import TextMulti from '../../../components/Input/TextMulti';
import {connect} from 'react-redux';
import {
  getFontXD,
  HEIGHTXD,
  toPriceVnd,
  checkFormatArray,
  WIDTHXD,
} from '../../../Config/Functions';
import PickerItem from '../../../components/Picker/PickerItem';
import RadioForm from 'react-native-simple-radio-button';
import {getListWidthDraw} from '../../../apis/Functions/Widthdraw';
import {useNavigation} from '@react-navigation/native';
import {showLoading, hideLoading} from '../../../actions/loadingAction';
import {saveUserToRedux} from '../../../actions/users';
import {confirmAlert} from '../../../components/Aleart';
import {
  ADDMETHODPAY,
  ENTER_PASSWORD_SMART_OTP,
  SETTINGOTP,
  CHANGESMARTOTP,
} from '../../../routers/ScreenNames';
import TextMoney from '../../../components/Input/InputMoney';
import I18n from '../../../helper/i18/i18n';
import {SMARTOTP} from '../../../routers/ScreenNames';
import {showAlert, TYPE} from '../../../components/DropdownAlert';
var radio_props = [
  {label: 'Từ ví', value: 'WALLET'},
  {label: 'Từ tài khoản CQG', value: 'INVESTMENT'},
];

var radio_propsEN = [
  {label: 'From wallet', value: 'WALLET'},
  {label: 'From CQG Account', value: 'INVESTMENT'},
];
const {width} = Dimensions.get('window');

const WalletWithdraw = (props) => {
  const [data, setData] = useState([]);
  const [src, setSrc] = useState('WALLET');
  const [type, setType] = useState();
  const [amount, setAmount] = useState();
  const [notes, setNotes] = useState('');

  const navigate = useNavigation();

  useEffect(() => {
    const unsubscribe = navigate.addListener('focus', () => {
      getData();
    });

    return unsubscribe;
  }, [navigate]);

  const getData = async () => {
    props.showLoading();
    const res = await getListWidthDraw({
      platform: Platform.OS,
    });
    if (res.data.code == 200 && res.data.data) {
      if (res.data.data.length == 0) {
        confirmAlert(I18n.t('SettingPaymentMethodConfirm'), () =>
          navigate.navigate(ADDMETHODPAY),
        );
      } else {
        const newList = res.data.data.map((e) => {
          return {...e, value: e.id, name: e.method};
        });
        setData(newList);
      }
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
    }
    props.hideLoading();
  };

  const onPressWithdraw = async () => {
    console.log();
    const titles = [
      I18n.t('BeneficiaryAccount'),
      I18n.t('AmountOfMoney').toLowerCase(),
    ];

    const index = checkFormatArray([type, amount]);

    if (index === true) {
      if (amount >= props.user.configs.request_withdraw_amount_min) {
      //   if (src == 'WALLET' && amount > props.user.current_money) {
      //     showAlert(
      //       TYPE.WARN,
      //       I18n.t('Notification'),
      //       I18n.t('WarnMaxReqestWithdraw'),
      //     );
      //   } else if (
      //     src == 'INVESTMENT' &&
      //     amount > props.user.current_cqg_money
      //   ) {
      //     showAlert(
      //       TYPE.WARN,
      //       I18n.t('Notification'),
      //       I18n.t('WarnMaxReqestWithdraw'),
      //     );
      //   } else {
          if (!props.user.smart_otp_status) {
            confirmAlert(
              `${I18n.t('YouHaveNotSettingSmartOTP')}`,
              () => {
                navigate.navigate(CHANGESMARTOTP, {
                  TYPE: 'CREATE_SMART_OTP',
                  old_password: null,
                  isFromTransaction: true,
                  setupSmartOTPSuccess: () => {
                    navigate.goBack();
                    navigate.goBack();
                    navigate.navigate(ENTER_PASSWORD_SMART_OTP, {
                      type: 'WITHDRAW',
                      onGoToSmartOTP: (pinCode, otp) =>
                        onGoToSmartOTP(pinCode, otp),
                    });
                    DeviceEventEmitter.emit('reloadUserInfo');
                  },
                });
              },
              `${I18n.t('setting')}`,
            );
          } else {
            navigate.navigate(ENTER_PASSWORD_SMART_OTP, {
              type: 'WITHDRAW',
              onGoToSmartOTP: (pinCode, otp) => onGoToSmartOTP(pinCode, otp),
            });
          }
      //   }
      } else {
        showAlert(
          TYPE.WARN,
          I18n.t('Notification'),
          I18n.t('WarnMinReqestWithdraw'),
        );
      }
    } else {
      showAlert(
        TYPE.WARN,
        I18n.t('Notification'),
        I18n.t('Please_fill_in') + titles[index],
      );
    }
  };

  const onGoToSmartOTP = (pinCode, otp) => {
    navigate.goBack();
    navigate.navigate(SMARTOTP, {
      type: 'WITHDRAW',
      src,
      receiving_account: type.id,
      amount,
      notes,
      pinCode,
      otp,
    });
  };

  return (
    <KeyboardAvoidingView
      behavior={Platform.Os === 'ios' ? 'padding' : 'height'}
      style={{flex: 1}}
      keyboardVerticalOffset={-50}>
      <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View style={{flex: 1}}>
          <HeaderBack title={'Withdraw'} />
          <ScrollView showsVerticalScrollIndicator={false}>
            <View style={styles.container}>
              <View style={styles.wrapTop}>
                <View style={styles.itemTop}>
                  <Text style={styles.txtTitle}>{I18n.t('Wallet')}</Text>
                  <Text style={styles.txtMoney}>
                    {' '}
                    {props.user.current_money != 0
                      ? toPriceVnd(props.user.current_money)
                      : 0}{' '}
                  </Text>
                </View>

                <View style={{width: 1, backgroundColor: '#DBDBDB'}} />

                <View style={styles.itemTop}>
                  <Text style={styles.txtTitle}>CQG</Text>
                  <Text style={styles.txtMoney}>
                    {props.user.current_cqg_money != 0
                      ? toPriceVnd(props.user.current_cqg_money)
                      : 0}{' '}
                    đ
                  </Text>
                </View>
              </View>
              <View style={styles.wrapBody}>
                <Text
                  style={{
                    fontSize: getFontXD(42),
                    color: R.colors.color777,
                  }}>
                  {I18n.t('SourceAccount')}
                </Text>
                {/* <View style={styles.row}> */}
                <RadioForm
                  radio_props={
                    props.language.language == 'vi'
                      ? radio_props
                      : radio_propsEN
                  }
                  labelStyle={{fontSize: getFontXD(42)}}
                  formHorizontal={true}
                  style={styles.row}
                  initial={0}
                  onPress={(value) => {
                    setSrc(value);
                  }}
                />
                {/* </View> */}
                <Text
                  style={{
                    fontSize: getFontXD(42),
                    color: R.colors.color777,
                  }}>
                  {I18n.t('ChooseBeneficiaryAccount')}
                </Text>
                <PickerItem
                  width={width - 20}
                  data={data}
                  onValueChange={(value, items) => {
                    setType(items);
                  }}
                />
                <TextMoney
                  onChangeText={(val) => setAmount(val)}
                  title={I18n.t('AmountOfMoney')}
                  value={amount}
                />
                <TextMulti
                  onChangeText={(val) => setNotes(val)}
                  title={I18n.t('Note')}
                  placeholder={I18n.t('noteWithdrawMoney')}
                />
              </View>
            </View>
          </ScrollView>

          <View
            style={{
              paddingVertical: 10,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <TouchableOpacity onPress={onPressWithdraw} style={styles.btnSend}>
              <Text style={styles.txtSend}>{I18n.t('Withdraw')}</Text>
            </TouchableOpacity>
          </View>
        </View>
      </TouchableWithoutFeedback>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: R.colors.white,
    marginVertical: 10,
    shadowColor: '#AFA9A9',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.25,
    shadowRadius: 1.84,
    elevation: 1,
  },
  wrapTop: {
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#DBDBDB',
  },
  itemTop: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 20,
  },
  wrapBody: {
    paddingHorizontal: 10,
    paddingVertical: 20,
  },
  txtMoney: {
    color: '#1C6AF6',
    fontSize: getFontXD(52),
  },
  txtTitle: {
    color: R.colors.black,
    fontSize: getFontXD(42),
  },
  txtSend: {
    fontSize: getFontXD(42),
    color: R.colors.white,
    fontWeight: 'bold',
  },
  btnSend: {
    width: WIDTHXD(400),
    height: HEIGHTXD(120),
    backgroundColor: R.colors.main,
    borderRadius: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  row: {
    height: HEIGHTXD(109),
    width: '100%',
    justifyContent: 'space-between',
    marginVertical: 5,
  },
});

const mapStateToProps = (state) => {
  return {
    user: state.userReducer,
    language: state.languageReducer,
  };
};
export default connect(mapStateToProps, {
  showLoading,
  hideLoading,
  saveUserToRedux,
})(WalletWithdraw);
