import React, {Component, useState, useEffect, useRef} from 'react';
import {View, Text, Platform, FlatList} from 'react-native';
import {getListCalendar} from '../../../apis/Functions/NewFeed';
import {convertTimeApi} from '../../../Config/Functions';

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 {
      Alert.alert('Thông báo', 'Không lấy được dữ liệu!');
    }
  };

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

      setTimeout(() => {
        ListDayRef.current.scrollToIndex({
          animated: true,
          index: index,
        });
      }, 200);
    }
  };

  const getItemLayout = (data, index) => ({
    length: 100,
    offset: 60 * index,
    index,
  });

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: 'white',
        paddingLeft: 10,
        paddingRight: 20,
        paddingTop: 10,
      }}>
      <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;
