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';

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 () => {
    const res = await getListMethod({
      platform: Platform.OS,
    });
    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}}>
        <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})(MethodPayView);