import React, {Component, useState, useEffect, useRef} from 'react';
import {View, Text, Platform, FlatList} from 'react-native';
import {getListCalendar} from '../../../apis/Functions/NewFeed';
import {showAlert, TYPE} from '../../../components/DropdownAlert';
import {convertTimeApi} from '../../../Config/Functions';
import I18n from '../../../helper/i18/i18n';
import AppText from '../../../components/AppText';

import Item from './item';
const NewFeed = (props) => {
  const [data, setData] = useState([]);
  const ListDayRef = useRef(null);

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

  const getData = async () => {
    var date = new Date(),
      y = date.getFullYear(),
      m = date.getMonth();
    var firstDay = new Date(y, m, 1);
    var lastDay = new Date(y, m + 1, 0);
    const res = await getListCalendar({
      platform: Platform.OS,
      start_date: convertTimeApi(firstDay),
      end_date: convertTimeApi(lastDay),
      keyword: '',
    });

    if (res.data.code == 200 && res.data.data) {
      setData(res.data.data);
    } else {
      showAlert(TYPE.ERROR, I18n.t('Notification'), I18n.t('Can_not_get_data'));
    }
  };

  const scrollToCurrent = () => {
    const date = new Date();
    let index = 0;
    const today = convertTimeApi(date);
    if (data.length > 0) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].start_date.substring(0, 10) == today) {
          index = i;
          break;
        } else {
          index = data.length - today.substring(8);
        }
      }
      setTimeout(() => {
        if (index > 0) {
          ListDayRef.current.scrollToIndex({
            animated: true,
            index: index,
          });
        }
      }, 200);
    }
  };
  const getItemLayout = (data, index) => ({
    length: 100,
    offset: 50 * index,
    index,
  });

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: 'white',
        paddingTop: 10,
      }}>
      {data.length == 0 ? (
        <View style={{justifyContent: 'center', alignItems: 'center', flex: 1}}>
          <AppText
            i18nKey={'NoData'}
            style={{
              fontSize: 18,
              fontWeight: 'bold',
            }}></AppText>
        </View>
      ) : (
        <FlatList
          ref={ListDayRef}
          getItemLayout={getItemLayout}
          data={data}
          showsVerticalScrollIndicator={false}
          keyExtractor={(item) => item.id}
          renderItem={({item, index}) => <Item item={item} index={index} />}
        />
      )}
    </View>
  );
};

export default NewFeed;
