import React, { useState, useEffect } from 'react';
import { SafeAreaView, StyleSheet, View, Text, FlatList, TouchableOpacity } from 'react-native';
import { Button } from 'react-native-elements';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { getDateStr } from '../utils/dateFunction';

const DateItem = ({ dateitem, textColor, onPress, flatListHeight }) => {
  return (
    <TouchableOpacity onPress={onPress}
      style={[style.dateContainer, { height: flatListHeight }]}>
      <Text style={textColor}>{dateitem.date.getDate()}</Text>
      {
        dateitem.type &&
        <View>
          <Text style={{ color: '#1E90FF' }}>{dateitem.type.input ? dateitem.type.input : null}</Text>
          <Text style={{ color: '#DC143C' }}>{dateitem.type.output ? dateitem.type.output : null}</Text>
        </View>
      }
    </TouchableOpacity>
  );
};

function Calendar({
  navigation,
  MData,
  year,
  setYear,
  month,
  setMonth,
  todayM,
  todayY,
}) {
  const date = new Date();
  const [flatListHeight, setFlatListHeight] = useState(400)

  const prevLast = new Date(year, month, 0);
  const thisFirst = new Date(year, month, 1); 
  const thisLast = new Date(year, month + 1, 0); 

  const thisFirstDay = thisFirst.getDay();
  const prevLastDate = prevLast.getDate(); 
  const thisLastDate = thisLast.getDate(); 
  const thisLastDay = thisLast.getDay(); 

  const Dates = [];
  const DBDates = [];
  if (thisFirstDay !== 0) { 
    for (let i = 0; i < thisFirstDay; i++) {
      Dates.unshift({ date: new Date(year, month - 1, prevLastDate - i) })
    }
  }
  for (let i = 1; i <= thisLastDate; i++) {
    Dates.push({ date: new Date(year, month, i) })
  }
  for (let i = 1; i <= 6 - thisLastDay; i++) {
    Dates.push({ date: new Date(year, month + 1, i) })
  }

  //DB 데이터와 날짜 비교
  for (let i = 0; i < MData.length; i++) {
    const str = MData[i].date
    DBDates.push({ date: new Date(Number(str.slice(0, 4)), Number(str.slice(5, 7)) - 1, Number(str.slice(8, 10))), type: MData[i].type })
  }

  for (let i = 0; i < Dates.length; i++) {
    const idx = DBDates.findIndex(obj => obj.date.getTime() === Dates[i].date.getTime())
    if (idx !== -1) {
      Dates[i] = DBDates[idx]
    }
  }

  let istoday = false;

  const renderDate = ({ item }) => {
    let color = '#000000';
    if (item.date.getDate() === date.getDate() && month === todayM && year === todayY) {
      istoday = true;
    }
    if (istoday) {
      color = '#6495ed'
      istoday = false;
    }
    if (!(item.date.getMonth() === month)) {
      color = '#a9a9a9'
    }

    return (
      <DateItem dateitem={item} textColor={{ color }} onPress={() => navigation.navigate('CalDetail', getDateStr(item.date))} flatListHeight={flatListHeight / (Dates.length / 7)} />
    )
  }
  const prevBtn = () => {
    if (month < 1) {
      setYear(year - 1)
      setMonth(11)
    } else {
      setMonth(month - 1)
    }
  };
  const nextBtn = () => {
    if (month > 10) {
      setYear(year + 1)
      setMonth(0)
    } else {
      setMonth(month + 1)
    }
  }
  useEffect(() => {
    setMonth(todayM)
    setYear(todayY)
  }, [])

  const onLayout = (event) => {
    const { x, y, height, width } = event.nativeEvent.layout;
    setFlatListHeight(height)
  }
  return (
    <>
      <SafeAreaView style={style.EntContainer}>
        <View style={style.Container}>
          <Text style={style.Head}>{year} 년 {month + 1} 월</Text>
          <View style={style.Buttons}>
            <Button icon={
              <Ionicons name='chevron-back-sharp' onPress={prevBtn} size={15} color='black' />
            } type='clear' />
            <Button title='Today' onPress={() => { setMonth(todayM); setYear(todayY) }} type='clear' />
            <Button icon={
              <Ionicons name='chevron-forward-sharp' onPress={nextBtn} size={15} color='black' />
            } type='clear' />
          </View>
        </View>
        <View style={style.Days}>
          <Text style={style.DayText}>월</Text>
          <Text style={style.DayText}>화</Text>
          <Text style={style.DayText}>수</Text>
          <Text style={style.DayText}>목</Text>
          <Text style={style.DayText}>금</Text>
          <Text style={style.DayText}>토</Text>
          <Text style={style.DayText}>일</Text>
        </View>
        <FlatList
          style={{ backgroundColor: "#FFFFFF" }}
          onLayout={onLayout}
          data={Dates}
          numColumns={7}
          renderItem={renderDate}
          keyExtractor={item => item.date}
        />
      </SafeAreaView>
    </>
  )
};

const style = StyleSheet.create({
  EntContainer: {
    flex: 1,
    padding: 20
  },
  Head: {
    fontSize: 24,
    fontFamily: 'GowunDodum-Regular'
  },
  Container: {
    justifyContent: "center",
    alignItems: "center",
  },
  dateContainer: {
    flex: 1,
    borderWidth: 0.8,
    borderColor: '#DCDCDC'
  },
  Buttons: {
    flexDirection: 'row',
    margin: 10
  },
  Days: {
    flexDirection: 'row',
    backgroundColor: '#6495ED'
  },
  DayText: {
    flex: 1,
    textAlign: 'center',
    color: '#FFFFFF',
    fontFamily: 'GowunDodum-Regular',
    fontWeight: "bold"
  },
});

export default Calendar;