import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TouchableOpacity, Modal, Alert, TouchableWithoutFeedback, Keyboard } from 'react-native';
import TodoItem from './components/TodoItem';
import Ionicons from 'react-native-vector-icons/Ionicons';
import ButtonsForm from './components/ButtonsForm'; 
import DeptForm from './screens/DeptForm';
import { TabView } from 'react-native-elements';
import deptApi from './db/deptPage.api';

function DeptPage({ navigation }) {
  const [lend, setLend] = useState([]) //빌려준
  const [dept, setDept] = useState([])  //빌린
  const [selectedIndex, setSelectedIndex] = useState(0)
  const [modallOpen, setModallOpen] = useState(false);

  const loadLend = async () => { //빌려준
    try {
      const deptArray = await deptApi.selectLoan("빌려준금액")

      setLend(deptArray);
    } catch (error) {
      console.log('error in load lend ( DeptPage.js )', error)
    }
  }

  const loadDept = async () => { //빌림
    try {
      const deptArray = await deptApi.selectLoan("빌린금액")
      setDept(deptArray);
    } catch (error) {
      console.log('error in load lend ( DeptPage.js )', error)
    }
  }

  const loadLoan = async () => {
    loadLend()
    loadDept()
  }

  const addInfo = async (info) => {
    if (selectedIndex) {
      info['loan'] = "빌린금액"
    } else {
      info['loan'] = "빌려준금액"
    }
    await deptApi.insertDept(info)
    setModallOpen(false); //modal이 보여지지 않게
    loadLoan()
  }

  const onDeleteHandle = async (id) => {
    await deptApi.deleteDept(id)
    loadLoan()
  }

  useEffect(() => { //처음 화면에 띄어지는거
    loadLoan()
  }, [])


  console.log(selectedIndex)
  return (
    <TouchableWithoutFeedback onPress={() => {
      Keyboard.dismiss();
    }}>
      <View Style={style.container}>
        <ButtonsForm
          onPress={(index) => {
            setSelectedIndex(index)
          }}
          selectedIndex={selectedIndex}
          group={["빌려준금액", "빌린금액"]} />

        <View>
          <View style={{ width: '100%', height: '75%' }}>
            <TabView value={selectedIndex} onChange={setSelectedIndex} >
              <TabView.Item style={{ width: '100%', height: '100%' }}>
                <FlatList
                  data={lend}
                  renderItem={({ item }) => (
                    <TouchableOpacity onPress={() => navigation.navigate('DeptDetails', { item: item, loadLoan: loadLend })}>
                      <TodoItem item={item} onDeleteHandle={() => onDeleteHandle(item.id)} />
                    </TouchableOpacity>
                  )}
                />
              </TabView.Item>
              <TabView.Item style={{ width: '100%', height: '100%' }}>
                <FlatList
                  data={dept}
                  renderItem={({ item }) => (
                    <TouchableOpacity onPress={() => navigation.navigate('DeptDetails', { item: item, loadLoan: loadDept })}>
                      <TodoItem item={item} onDeleteHandle={() => onDeleteHandle(item.id)} />
                    </TouchableOpacity>
                  )}
                />
              </TabView.Item>
            </TabView>
          </View>
          <Ionicons
            name='add'
            size={24}
            style={style.modalToggle} 
            onPress={() => setModallOpen(true)}
          />
        </View>
        <View>
          <Modal visible={modallOpen} animationType='slide'>
            <View style={style.modalContent}>
              <Ionicons
                name='close'
                size={24}
                style={style.modalToggle}
                onPress={() => setModallOpen(false)}
              />
              <DeptForm addInfo={addInfo} />
            </View>
          </Modal>
        </View>
      </View>
    </TouchableWithoutFeedback >
  );
}

const style = StyleSheet.create({
  Font: {
    fontFamily: 'GowunDodum-Regular'
  },

  container: {
    fontFamily: 'GowunDodum-Regular',
    flex: 1,
    width: '100%',
  },
  modalToggle: {
    borderWidth: 1,
    borderColor: 'gray', //gray
    padding: 5,
    borderRadius: 10,
    alignSelf: 'center', //위치를 center로
  },

  modalContent: {
    flex: 1, //이후 유용한 키보드를 추가하려고 ex)dismissing keyboard
  }

});

export default DeptPage;
