import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import TodoModal from "../components/Modal/TodoModal";
import TodoPostModal from "../components/Modal/TodoPostModal";
import todoApi from "../apis/todo.api";
import { useAuth } from "../utils/context";
import catchErrors from "../utils/catchErrors";
import moment from "moment";
import styles from "../components/Form/form.module.scss";

const TodoList = () => {
  const { user } = useAuth()
  const { date } = useParams()
  const [todoList, setTodoList] = useState([])
  const [selectTodo, setSelectTodo] = useState(null)
  const [error, setError] = useState("");

  useEffect(() => {
    getAll()
  }, [date])

  async function getAll() {
    try {
      setError("")
      const resList = await todoApi.getTodo(user.id, date)
      setTodoList(resList)
    } catch (error) {
      catchErrors(error, setError)
    }
  }

  async function delayTodo() {
    try {
      setError("")
      const nextDate = moment(date).add(1, 'day').format("YYYY-MM-DD")
      await todoApi.edit({ id: selectTodo.id, todoDate: nextDate }, user.id)
      getAll()
    } catch (error) {
      catchErrors(error, setError)
    }
  }

  async function delTodo(todoId) {
    try {
      setError("")
      await todoApi.remove(todoId, user.id)
      alert("해당 할일이 성공적으로 삭제되었습니다.")
      getAll()
    } catch (error) {
      catchErrors(error, setError)
    }
  }

  return (
    <div className={"mt-3 " + (todoList.length ? "d-flex flex-column" : "d-block")}>
      {todoList.length !== 0 ?
        todoList.map((todo, idx) => <div className="d-flex">
          <div className="d-flex align-items-center" style={{ width: "75%" }}>
            <input className={`form-check-input rounded-0 shadow-none mt-0 me-2 ${styles.checkBox}`} type="checkbox" checked={todo.done} />
            <label className="form-check-label fs-5 pe-2 text-nowrap" style={{ overflow: "hidden", textOverflow: "ellipsis" }}>{todo.todoTitle}</label>
          </div>
          <div className="d-flex justify-content-between" style={{ cursor: "pointer", width: "25%" }}>
            <i className="bi bi-arrow-right fs-5" data-bs-toggle="modal" data-bs-target="#postmodal" onClick={() => setSelectTodo(todo)}></i>
            <i className="bi bi-pencil-square fs-5" data-bs-toggle="modal" data-bs-target="#todomodal" onClick={() => setSelectTodo(todo)}></i>
            <i className="bi bi-trash fs-5" onClick={() => delTodo(todo.id)}></i>
          </div>
        </div>) : <p className="text-center">등록된 할일이 없습니다.</p>}
      <TodoPostModal handleClick={delayTodo} />
      <TodoModal curDate={date} selectTodo={selectTodo} />
    </div>
  )
}

export default TodoList;