import React, { useState } from 'react';
import { StyleSheet, Text, View, FlatList, TouchableOpacity, Modal, Alert, TouchableWithoutFeedback, Keyboard } from 'react-native';
import Header from './components/header';
import AddTodo from './components/addTodo';
import TodoItem from './components/todoItem';
import InfoForm from './screens/infoForm';
import { globalStyles } from './styles/global';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Infodetails from './screens/InfoDetails'
import ButtonsForm from './components/ButtonsForm';
import StyledButton from './components/StyledButton';
import { NavigationContainer } from '@react-navigation/native';


export default function DeptPage({ navigation }) {
  const [selectedIndex, setSelectedIndex] = useState(0)
  const [modallOpen, setModallOpen] = useState(false);
  const [todos, setTodos] = useState([
    { date: '7/10', person: '수빈이', money: '100만원', remaied_money: '10만원남음', key: '1' },
    { date: '7/10', person: '수현이', money: '100만원', remaied_money: '10만원남음', key: '2' },
    { date: '7/10', person: '가영이', money: '100만원', remaied_money: '10만원남음', key: '3' }
  ]);

  const addInfo = (info) => {
    info.key = Math.random().toString(); //앞에 key를 받아올수있도록 생성
    setTodos((currentInfos) => {
      return [info, ...currentInfos]; //새로운 정보와 지금까지 정보를 합친다
    });
    setModallOpen(false); //modal이 보여지지 않게
  }

  const pressHandler = (key) => {
    setTodos((prevTodos) => {
      return prevTodos.filter(todo => todo.key != key);
    });
  }



  // const [modalOpen, setModalOpen] = useState(false);
  // //이 함수로 내용 추가를 함 Addtodo함수에서 이용
  // const submitHandler = (text) => {
  //   //alert를 사용하기위해 조건문 지정
  //   if (text.length > 3) {
  //     setTodos((prevTodos) => {
  //       return [
  //         { text: text, key: Math.random().toString() },
  //         ...prevTodos  //앞의 todos에 추가하여 내용을 더 추가함
  //       ];
  //     });
  //   } else { //3글자 보다 작으면 alert
  //     Alert.alert('OOPs!', '3글짜 이상!', [
  //       { text: 'Understood', onPress: () => console.log('alert closed') }//understood 버튼 누르면 alert꺼짐
  //     ]);
  //   }

  // }
  const insertData = async () => {
    try {
      if (selectedIndex === 0) { type = '빌려준금액' }
      else { type = '빌린금액' }

      (await db).transaction((tx) => {
        console.log("데이터 삽입하기");
        tx.executeSql('INSERT INTO Money (type, date, contents, price, asset_type, category) VALUES (?,?);',
          [expense, income],
          () => { console.log("삽입 성공"); },
          (error) => console.log(error))
      })
    } catch (error) {
      console.log('error in insert data', error)
    }
  }



  return (



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

        <View style={styles.list}>
          <FlatList
            data={todos}
            renderItem={({ item }) => (
              <TouchableOpacity onPress={() => navigation.navigate('InfoDetails', item)}>
                <TodoItem item={item} pressHandler={pressHandler} />
              </TouchableOpacity>
            )}
          />
          <View style={styles.content}>
            <Modal visible={modallOpen} animationType='slide'>
              <View style={style.modalContent}>
                <Ionicons
                  name='close'
                  size={24}
                  style={style.modalToggle}
                  onPress={() => setModallOpen(false)}
                />
                <InfoForm addInfo={addInfo} />

              </View>
            </Modal>
            <Ionicons
              name='add'
              size={24}
              style={{ ...style.modalToggle, ...style.modalClose }} //...은 중괄호를 풀어서 합치려고 이용함
              onPress={() => setModallOpen(true)}
            />
          </View>
        </View>
      </View>
    </TouchableWithoutFeedback>
  );
}



//content는 내용이 추가되면 계속 커진다
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  content: {
    padding: 40,
  },
  list: {
    marginTop: 20, //top에서부터 거리
  }
});

const style = StyleSheet.create({
  modalToggle: {
    marginBottom: 10,
    borderWidth: 1,
    borderColor: 'grey', //grey
    padding: 10,
    borderRadius: 10,
    alignSelf: 'center', //위치를 center로
  },
  modalClose: {
    alignSelf: 'center',
    alignItems: 'flex-end',
    marginTop: 130,
    marginBottom: 20,
  },
  modalContent: {
    flex: 1, //이후 유용한 키보드를 추가하려고 ex)dismissing keyboard
  },

  TextInput: {
    borderColor: 'skyblue',
    height: 40,
    margin: 12,
    borderWidth: 1
  },
  Font: {
    fontSize: 24
  }
});