import { Fragment, useEffect, useState } from 'react';
import './App.css'
import Modal from './Components/Modal';

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://localhost:3000/todos');
    if (!response.ok) {
      console.log("Error fetching data")
    }
    setTodoList(await response.json())
  }

  const saveTodo = async () => {
    try {
      if (newTodo !== '' && newTodo) {
        await fetch('http://localhost: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()
    console.log(todoItem, "todoItem.completed")
    await fetch(`http://localhost: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://localhost: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 onEditCancel = (e: any) => {
    setEditingTodoId(null);
    setEditableTitle('');
     e.stopPropagation()
  }

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

  return (
    <>
      <section className="layout-container">
        <div className="todo-container">
          <div className="header-section">
            {todoList?.length > 0 ? <>You have {todoList?.length} Todos </> : <>No Tasks</>}
          </div>

          {todoList?.map((ele: any, index: number) => (
            <Fragment key={ele.id}>
              <div className='checklist-item'>
                <div className='checklist-item__content' onClick={() => editTodo(ele.id)}>
 
                  <input type='checkbox' checked={ele.completed} className='custom-checkbox'  onClick={(e) => e.stopPropagation()} onChange={(e) => toggleTodo(ele,e)} />
                  {editingTodoId === ele.id ? (
                    <input type='text' value={editableTitle} className='checklist-item__editable-input' onChange={(e) => setEditableTitle(e.target.value)} />
                  ) : (
                    <h3 className={`checklist-item__title ${ele.completed ? 'strike' : ''}`} >{ele.title}</h3>
                  )}
                  {editingTodoId === ele.id && <span className='edit-action-btn' onClick={(e) => onEditCancel(e)}><img src='../src/assets/images/cancel-svgrepo-com.svg' width={30} /></span>}
                  {editingTodoId === ele.id && <span className='edit-action-btn' onClick={(e) => onSaveEdit(e, ele.id)}><img src='../src/assets/images/ok-svgrepo-com.svg' width={30} /></span>}
                </div>
                <div className=''>
                  <img className='checklist-item__remove-btn' width={40} src='../src/assets/images/close-round-svgrepo-com.svg' onClick={() => onDeleteTodo(ele)} />
                </div>
              </div>
              {index + 1 !== todoList.length && <hr className='divider' />}
            </Fragment>
          ))}
          <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>
          </div>
        </div>
        {openModal &&
          <Modal
            onCancel={() => setOpenModal(false)}
            onDelete={() => deleteTodo()}
          />}
      </section>
    </>

  )
}

export default App;
