import { Fragment, useEffect, useState } from 'react';
import './App.css'
import Modal from './Components/Modal';
import Header from './Components/Header/Header';
import CheckListItem from './Components/CheckListItem/CheckListItem';
import TodoInput from './Components/TodoInput/TodoInput';
import Button from './Components/Button/Button';
function App() {

  const [todoList, setTodoList] = useState<any>();
  const [newTodo, setNewTodo] = useState<any>('');
  const [openModal, setOpenModal] = useState(false);
  const [selectedTodo, setSelectedTodo] = useState<any>(null);
  const [editingTodoId, setEditingTodoId] = useState<any>(null);
  const [editableTitle, setEditableTitle] = useState('');


  useEffect(() => {
    fetchTodos();
  }, [])

  const fetchTodos = async () => {
    const response = await fetch('http://192.168.1.101:3000/todos', {
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (!response.ok) {
      console.log("Error fetching data")
    }
    setTodoList(await response.json())
  }

  const saveTodo = async () => {
    try {
      if (newTodo !== '' && newTodo) {
        await fetch('http://192.168.1.101:3000/todos', {
          method: 'POST',
          body: JSON.stringify({
            title: newTodo,
            completed: false
          })
        })
        fetchTodos();
      }
      setNewTodo("")
    } catch (error) {
      console.log(error, "error in adding todo")
    }
  }

  const toggleTodo = async (todoItem: any, e: any) => {
    e.stopPropagation()
    await fetch(`http://192.168.1.101:3000/todos/${todoItem.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ completed: !todoItem.completed })
    })
    fetchTodos();
  }



  const onDeleteTodo = (todo: any) => {
    setOpenModal(true);
    setSelectedTodo(todo)
  }

  const deleteTodo = async () => {

    if (selectedTodo) {
      await fetch(`http://192.168.1.101:3000/todos/${selectedTodo?.id}`, {
        method: "DELETE"

      })
      fetchTodos();
      setOpenModal(false)
    }
  }

  const editTodo = (todoId: any) => {
    setEditingTodoId(todoId);
    const editableTodo = todoList.find((ele: any) => ele.id === todoId);
    setEditableTitle(editableTodo?.title)
  }

  const onSaveEdit = async (e: any, todoId: any) => {
    e.stopPropagation();
    await fetch(`http://192.168.1.101:3000/todos/${todoId}`, {
      method: 'PATCH',
      body: JSON.stringify({
        title: editableTitle
      })
    });
    fetchTodos();
    setEditingTodoId(null)
    setEditableTitle("")
  }

  return (
    <>
      <section className="layout-container">
        <div className="todo-container">
          <Header todoList={todoList} />
          {todoList?.map((ele: any, index: number) => (
            <CheckListItem
              key={ele.id}
              ele={ele}
              editingTodoId={editingTodoId}
              editableTitle={editableTitle}
              editTodo={editTodo}
              toggleTodo={toggleTodo}
              setEditableTitle={setEditableTitle}
              onSaveEdit={onSaveEdit}
              todoList={todoList}
              index={index}
              onDeleteTodo={onDeleteTodo}
            />
          ))}
          <div className='form-group'>
            {/* <input value={newTodo} onChange={(e) => setNewTodo(e.target.value)} className='form__input' placeholder='Enter Item' />
            <button className='form__submit' onClick={saveTodo}>
              Submit
            </button> */}
            <TodoInput
              newTodo={newTodo}
              setNewTodo={setNewTodo}
            />
            <Button
              saveTodo={saveTodo}
            />
          </div>
        </div>
        {openModal &&
          <Modal
            onCancel={() => setOpenModal(false)}
            onDelete={() => deleteTodo()}
          />}
      </section>
    </>

  )
}

export default App;
