import { useLiveQuery } from "@tanstack/solid-db";
import { useTodoCollection } from "~/context/todocollection/create";
import { Todo } from './Todo'
import { For } from 'solid-js'

export const ListTodos = () => {
  const todoCollection = useTodoCollection()
  const data = useLiveQuery((q) =>
    q.from({todos: todoCollection})
  )
  const todos = () => {
    const items = Array.from(data.state.values());
    return items.sort((a: any, b: any) => {
      if (a.done != b.done) return a.done ? -1 : 1
      if (!a.done && !b.done) {
        const adate = a.createdAt ? new Date(a.createdAt) : new Date()
        const bdate = b.createdAt ? new Date(b.createdAt) : new Date()
        return bdate.getTime() - adate.getTime()
      }
      return 0
    })
  }

  return (
    <For each={todos()} fallback={<div>Loading...</div>}>
      {(item) => <Todo todo={item} />}
    </For>
  )
}
