import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  FlatList,
  Platform,
  Alert,
} from 'react-native';
import R from '../../../assets/R';
import {getFontXD} from '../../../Config/Functions';
import Item from './item';
import {getListNew, getListCategoryNew} from '../../../apis/Functions/NewFeed';
import I18n from '../../../helper/i18/i18n';
import AppText from '../../../components/AppText';
import {showAlert, TYPE} from '../../../components/DropdownAlert';

const NewFeed = (props) => {
  const [selected, setSelected] = useState('');
  const [page, setPage] = useState(1);
  const [data, setData] = useState([]);
  const [tottalPage, setTotalPage] = useState(1);
  const [isRefresh, setisRefresh] = useState(false);
  const [fillters, setFillters] = useState([]);

  const getCategory = async () => {
    const res = await getListCategoryNew({
      keyword: '',
      platform: Platform.OS,
      page_size: 20,
      page_index: 1,
    });
    if ((res.data.code = 200 && res.data.data)) {
      setFillters(res.data.data);
      console.log(res.data.data);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
  };

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

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

  const getData = async () => {
    setisRefresh(true);
    setPage(1);
    const res = await getListNew({
      keyword: '',
      category_id: selected,
      platform: Platform.OS,
      page_size: 10,
      page_index: 1,
    });
    if ((res.data.code = 200 && res.data.data)) {
      setData(res.data.data);
      setTotalPage(res.data.meta.pages);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), res.data.message);
    }
    setisRefresh(false);
  };

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

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

  const getDataLoadMore = async () => {
    setisRefresh(true);
    const res = await getListNew({
      keyword: '',
      category_id: selected,
      platform: Platform.OS,
      page_size: 10,
      page_index: page + 1,
    });
    setPage(page + 1);

    if (res.data.code == 200) {
      setData(data.concat(res.data.data));
    }
    setisRefresh(false);
  };

  return (
    <View style={{flex: 1, backgroundColor: 'white'}}>
      <View style={styles.fillterView}>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          <TouchableOpacity
            onPress={() => {
              setSelected('');
            }}
            style={[
              styles.item,
              selected == '' ? {backgroundColor: '#BCD7F8'} : {},
            ]}>
            <AppText
              i18nKey={'All'}
              style={[styles.txt, selected == '' ? {color: '#1C6AF6'} : {}]}
            />
          </TouchableOpacity>
          {fillters.map((e) => (
            <TouchableOpacity
              onPress={() => {
                setSelected(e.id);
              }}
              key={e.id + 'a'}
              style={[
                styles.item,
                e.id == selected ? {backgroundColor: '#BCD7F8'} : {},
              ]}>
              <Text
                style={[
                  styles.txt,
                  e.id == selected ? {color: '#1C6AF6'} : {},
                ]}>
                {e.name}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>
      <View style={{flex: 1, paddingHorizontal: 10}}>
        <FlatList
          showsVerticalScrollIndicator={false}
          keyExtractor={(item, index) => item.id + 'a'}
          refreshing={isRefresh}
          onRefresh={() => onRefresh()}
          onEndReachedThreshold={0.01}
          onEndReached={(info) => {
            onLoadMore();
          }}
          data={data}
          renderItem={({item}) => <Item item={item} />}
        />
      </View>
    </View>
  );
};

export default NewFeed;

const styles = StyleSheet.create({
  fillterView: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 10,
  },
  item: {
    backgroundColor: '#EBEBEB',
    marginRight: 5,
    paddingHorizontal: 10,
    paddingVertical: 6,
    marginLeft: 5,
    borderRadius: 10,
  },
  txt: {
    fontSize: getFontXD(42),
    color: R.colors.black,
    fontWeight: 'bold',
  },
});
