import React, { useState, useEffect } from 'react';
import { StyleSheet, View, FlatList, TouchableOpacity, Modal, 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); 
    loadLoan()
  }

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

  useEffect(() => { 
    loadLoan()
  }, [])

  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', 
    padding: 5,
    borderRadius: 10,
    alignSelf: 'center', 
  },

  modalContent: {
    flex: 1, 
  }

});

export default DeptPage;
