import React, {useEffect, useState} from 'react';
import {View, Text, StyleSheet, FlatList, Platform, Alert} from 'react-native';
import R from '../../../assets/R';
import HeaderBack from '../../../components/Header/HeaderBack';
import Item from './Item';
import {getListMethod} from '../../../apis/Functions/Deposit';
import {connect} from 'react-redux';
import I18n from '../../../helper/i18/i18n';
import {showAlert, TYPE} from '../../../components/DropdownAlert';
import {useNavigation} from '@react-navigation/native';
import {saveUserToRedux} from '../../../actions/users';
import {getDetailUser} from '../../../apis/Functions/users';
import AppText from '../../../components/AppText';
import {showLoading, hideLoading} from '../../../actions/loadingAction';

const MethodPayView = (props) => {
  const [data, setData] = useState([]);
  const navigation = useNavigation();

  useEffect(() => {
    getData();
  }, []);

  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      callApi();
    });

    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

  const callApi = async () => {
    const res = await getDetailUser({
      id: props.user.uid,
      platform: Platform.OS,
    });
    console.log(res);
    if (res.data.code == 200 && res.data.data) {
      props.saveUserToRedux(res.data.data);
    }
  };

  const getData = async () => {
    props.showLoading();
    const res = await getListMethod({
      platform: Platform.OS,
    });
    props.hideLoading();
    if (res.data.code == 200 && res.data.data) {
      setData(res.data.data);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
  };

  return (
    <View style={{flex: 1}}>
      <HeaderBack title={'SelectPaymentMethod'} />
      <View style={{flex: 1}}>
        {data.length == 0 ? (
          <View
            style={{justifyContent: 'center', alignItems: 'center', flex: 1}}>
            <AppText
              i18nKey={'NoData'}
              style={{
                fontSize: 18,
                fontWeight: 'bold',
              }}></AppText>
          </View>
        ) : (
          <FlatList
            keyExtractor={(item) => item.id}
            showsVerticalScrollIndicator={false}
            numColumns={2}
            columnWrapperStyle={{
              marginHorizontal: 20,
              justifyContent: 'space-between',
            }}
            data={data}
            renderItem={({item}) => (
              <Item userId={props.user.uid} item={item} />
            )}
          />
        )}
      </View>
    </View>
  );
};

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