import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  Platform,
  Alert,
  TouchableWithoutFeedback,
  Keyboard,
  KeyboardAvoidingView,
  ScrollView,
} from 'react-native';
import R from '../../../assets/R';
import HeaderBack from '../../../components/Header/HeaderBack';
import TextField from '../../../components/Input/TextField';
import TextMulti from '../../../components/Input/TextMulti';
import TextDisable from '../../../components/Input/TextDisable';
import {connect} from 'react-redux';
import {
  getFontXD,
  HEIGHTXD,
  toPriceVnd,
  checkFormatArray,
} from '../../../Config/Functions';
import PickerItem from '../../../components/Picker/PickerItem';
import RadioForm from 'react-native-simple-radio-button';
import {widthDraw, getListWidthDraw} from '../../../apis/Functions/Widthdraw';
import {useNavigation} from '@react-navigation/native';
import {showLoading, hideLoading} from '../../../actions/loadingAction';
import {confirmAlert} from '../../../components/Aleart';
import {ADDMETHODPAY} from '../../../routers/ScreenNames';
import TextMoney from '../../../components/Input/InputMoney';
import I18n from '../../../helper/i18/i18n';
var radio_props = [
  {label: I18n.t('FromWallet'), value: 'WALLET'},
  {label: I18n.t('FromCQGAccount'), 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 () => {
    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 {
      Alert.alert(I18n.t('Notification'), I18n.t('Can_not_get_data'));
    }
  };

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

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

    if (index === true) {
      props.showLoading();
      const res = await widthDraw({
        src,
        receiving_account: type.id,
        amount,
        platform: Platform.OS,
        notes,
        fee: 0,
      });

      props.hideLoading();

      if (res.data.code == 200) {
        setTimeout(() => {
          Alert.alert(I18n.t('Notification'), res.data.message);
          navigate.goBack();
        }, 500);
      } else {
        setTimeout(() => {
          Alert.alert(I18n.t('Notification'), res.data.message);
        }, 500);
      }
    } else {
      Alert.alert(
        I18n.t('Notification'),
        I18n.t('Please_fill_in') + titles[index],
      );
    }
  };

  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={radio_props}
                  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')}
                />
              </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: 140,
    height: 40,
    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,
  };
};
export default connect(mapStateToProps, {
  showLoading,
  hideLoading,
})(WalletWithdraw);
