import React, {useState, useEffect} from 'react';
import {View, Text, FlatList} from 'react-native';
import HeaderBack from '../../../../components/Header/HeaderBack';
import Item from './Item';
import {getListTransaction} from '../../../../apis/Functions/Widthdraw';
import {useNavigation} from '@react-navigation/native';
import AppText from '../../../../components/AppText';

import I18n from '../../../../helper/i18/i18n';

const Watting = (props) => {
  const [page, setPage] = useState(1);
  const [data, setData] = useState([]);
  const [tottalPage, setTotalPage] = useState(1);
  const [isRefresh, setisRefresh] = useState(false);
  const navigation = useNavigation();

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

    return unsubscribe;
  }, [navigation]);

  const getData = async () => {
    setisRefresh(true);
    setPage(1);
    const res = await getListTransaction({
      keyword: '',
      type: 'ALL',
      platform: Platform.OS,
      page_size: 10,
      status: 0,
      page_index: 1,
      start_date: '',
      end_date: '',
    });
    setisRefresh(false);
    if ((res.data.code = 200 && res.data.data)) {
      setData(res.data.data);
      setTotalPage(res.data.meta.pages);
    } else {
      Alert.alert(I18n.t('Notification'), res.data.message);
    }
  };

  const onRefresh = () => {
    getData();
  };

  const onLoadMore = () => {
    if (page < tottalPage) getDataLoadMore();
  };

  const getDataLoadMore = async () => {
    setisRefresh(true);
    const res = await getListTransaction({
      keyword: '',
      type: 'ALL',
      platform: Platform.OS,
      page_size: 10,
      status: -1,
      page_index: page + 1,
      start_date: '',
      end_date: '',
    });
    setPage(page + 1);
    if (res.data.code == 200) {
      setData(data.concat(res.data.data));
    }
    setisRefresh(false);
  };

  return (
    <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.transection_id + 'a'}
          refreshing={isRefresh}
          onRefresh={onRefresh}
          onEndReachedThreshold={0.01}
          onEndReached={(info) => {
            onLoadMore();
          }}
          data={data}
          renderItem={({item}) => <Item item={item} />}
        />
      )}
    </View>
  );
};

export default Watting;
