import { ExtractPayload, type Todo as RpcTodo } from '@<@var(context.project.name)>/rpc'
import { createSignal, type JSX } from 'solid-js';
import { useTodoCollection } from '~/context/todocollection/create';

export const Todo = ({ todo }: { todo: ExtractPayload<RpcTodo> }) => {
  const [todoState, setTodoState] = createSignal(todo)
  const todoCollection = useTodoCollection()
  let commitUpdateTimeoutId: NodeJS.Timeout|null = null;
  const updateTask: JSX.EventHandlerUnion<HTMLInputElement, Event> = (e) => {
    if (commitUpdateTimeoutId != null) {
      clearTimeout(commitUpdateTimeoutId)
    }
    const todo = { ...todoState() };
    todo.task = e.currentTarget.value
    setTodoState(todo)
    commitUpdateTimeoutId = setTimeout(() => {
      todoCollection.update(todoState().id, (draft) => {
        draft.task = todoState().task
      })
    },3000)

  }
  const updateDone: JSX.EventHandlerUnion<HTMLInputElement, Event> = (e) => {
    const todo = { ...todoState() }
    todo.done = e.currentTarget.checked
    setTodoState(todo)
    todoCollection.update(todoState().id, (draft) => {
      draft.done = todoState().done
    })
  }
  const del = () => {
    todoCollection.delete(todoState().id || "")
  }
  return (
    <div class="flex flex-col items-center border rounded-md p-5 gap-2">
      <input class="text-center border rounded-md px-3 py-1" oninput={updateTask} type="text" value={todoState().task} />
      <span> {(new Date(todoState().createdAt || "")).toLocaleString()}</span>
      <span> {(new Date(todoState().updatesAt || "")).toLocaleString()}</span>
      <input type="checkbox" onchange={updateDone} checked={todoState().done} />
      <button class="bg-amber-800 text-amber-100 p-1 rounded-md cursor-pointer" onclick={del} class=""> delete </button>
    </div>
  )
}

