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>
  );
};
const INIT_Data = [
  {
    date: "2021-06-28",
    type: { 'input': 10000, 'output': 1000 },
  },
  {
    date: "2021-07-01",
    type: { 'input': 50000, 'output': 3500 },
  },
  {
    date: "2021-07-11",
    type: { 'input': 100000, 'output': 2000 },
  },
  {
    date: "2021-08-14",
    type: { 'input': 15000, 'output': 2010 },
  },
];

function Calendar({
  navigation,
  MData,
  year,
  setYear,
  month,
  setMonth,
  todayM,
  todayY,
}) {
  //console.log('MData', MData)
  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;