import KV from "@workshop/shared/kv"
import { submitAction, useAction, type Head, type LoaderProps } from "@workshop/nano-remix"
import { useCallback } from "hono/jsx/dom"
import { TodoEditor } from "../../todoEditor"
import { debounce } from "@workshop/shared/utils"
import "../../index.css"

export const head: Head = {
  title: "Todos",
}

export const loader = async (_req: Request, params: { id: string }) => {
  const todos = await KV.get("todos", {})
  return { todos: todos![params.id] }
}

export const action = async (req: Request, params: { id: string }) => {
  const formData = await req.formData()
  const todosString = formData.get("todos") as string
  await KV.update("todos", {}, (todos) => {
    todos[params.id] = todosString
    return todos
  })

  return { success: true }
}

const debounceSubmit = debounce((todos: string) => submitAction({ todos }), 2000)

export default ({ todos }: LoaderProps<typeof loader>) => {
  const { error } = useAction<typeof action>()

  const handleChange = useCallback(async (newTodos: string) => {
    debounceSubmit(newTodos)
  }, [])

  return (
    <div class="min-h-screen flex flex-col">
      <div class="grow flex">
        <TodoEditor defaultValue={todos} onChange={handleChange} />
      </div>
      {error && <div class="text-right p-1 text-red-500">Error: {error}</div>}
    </div>
  )
}
