import React, { useState } from 'react';
import { SafeAreaView, View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';
import calApi from './db/calendarInfo.api';
const DetailItem = ({ item, onPress }) => {
  let item_color
  switch (item.type) {
    case 1:
      item_color = style.inputColor;
      break;
    case 2:
      item_color = style.outputColor;
      break;
    case 3:
      item_color = style.moveColor;
      break;
  }

  return (
    <TouchableOpacity onPress={onPress}>
      <View style={{
        padding: "5%", borderColor: '#d3d3d3', //light grey
        borderWidth: 1, borderTopWidth: 0,
      }}>
        <View style={{ flexDirection: "row" }}>
          <Text style={[style.itemText, item_color]}>{item.category}</Text>
          <Text style={[style.itemTextNum, style.Font]}>{item.contents}</Text>
          <Text style={[style.itemTextNum, style.Font]}>{(item.price).toLocaleString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}원</Text>
        </View>
        {item.asset ?
          <Text style={[style.itemTextNum, style.Font]}>
            {'(' + item.asset + '>' + item.deposit_asset + ')'}
          </Text>
          : null}

      </View>
    </TouchableOpacity>
  );
};

const DetailInfo = ({ route, navigation }) => {
  const [resData, setResData] = useState([])
  const getDetailData = async () => {
    try {
      const resdata = await calApi.detailData({ findDate: route.params })
      setResData(resdata)
    } catch (error) {
      console.log('error in getDetailData', error)
    }
  }
  const renderDetail = ({ item }) => {
    return (
      <DetailItem item={item} onPress={() => navigation.navigate('UpdatePage', [route.params, item])} />
    )
  }

  useFocusEffect(
    React.useCallback(() => {
      getDetailData()
    }, [])
  );

  return (
    <>
      <SafeAreaView>
        {
          resData.length !== 0 ? <FlatList
            data={resData}
            renderItem={renderDetail}
            keyExtractor={item => item.id}
          /> : <View style={{ margin: "20%" }}>
            <Text style={{ textAlign: "center", fontSize: 20, fontFamily: 'GowunDodum-Regular' }}>내역이 없습니다.</Text>
          </View>
        }
      </SafeAreaView>
    </>
  )
}
const style = StyleSheet.create({
  Font: {
    fontSize: 20,
    color: '#424242'
  },
  inputColor: {
    color: '#1E90FF'
  },
  outputColor: {
    color: '#dc143c'
  },
  itemTextNum: {
    flex: 1,
    textAlign: "center",
    fontFamily: 'GowunDodum-Regular'
  },
  itemText: {
    flex: 1,
    fontFamily: 'GowunDodum-Regular'
  },
  moveColor: {
    color: '#646d75'
  }
});

export default DetailInfo;