import React, {Component, useState, useEffect} from 'react';
import {View, Text, FlatList} from 'react-native';
import Item from '../Item';
import {getListPartner} from '../../../../apis/Functions/users';
import {showAlert, TYPE} from '../../../../components/DropdownAlert';
import AppText from '../../../../components/AppText';
import I18n from '../../../../helper/i18/i18n';

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

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

  const getData = async () => {
    setisRefresh(true);
    setPage(1);
    const res = await getListPartner({
      keyword: '',
      level: props.type,
      platform: Platform.OS,
      page_size: 10,
      page_index: 1,
      trader_account_status: -1,
    });

    if ((res.data.code = 200 && res.data.data && res.data.data.length > 0)) {
      setData(res.data.data);
      setTotalPage(res.data.meta.pages);
    } else {
      setData([]);
    }
    setisRefresh(false);
  };

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

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

  const getDataLoadMore = async () => {
    setisRefresh(true);

    const res = await getListPartner({
      keyword: '',
      level: props.type,
      platform: Platform.OS,
      page_size: 10,
      page_index: page + 1,
      trader_account_status: -1,
    });
    setPage(page + 1);

    console.log('rress', res);
    if (res.data.code == 200 && res.data.data && res.data.data.length > 0) {
      setData(data.concat(res.data.data));
    }
    setisRefresh(false);
  };

  return (
    <View style={{flex: 1}}>
      {data.length > 0 ? (
        <FlatList
          data={data}
          showsVerticalScrollIndicator={false}
          keyExtractor={(item) => item.id}
          refreshing={isRefresh}
          onRefresh={() => onRefresh()}
          onEndReachedThreshold={0.01}
          onEndReached={(info) => {
            console.log('Cham');
            onLoadMore();
          }}
          renderItem={({item, index}) => (
            <Item
              isSearch={false}
              level={props.type}
              isEnd={data.length - 1 == index ? true : false}
              item={item}
            />
          )}
        />
      ) : (
        <View style={{justifyContent: 'center', alignItems: 'center', flex: 1}}>
          <AppText
            i18nKey={'NoData'}
            style={{
              fontSize: 18,
              fontWeight: 'bold',
            }}></AppText>
        </View>
      )}
    </View>
  );
};

export default Level1;
