import { createRoot } from "react-dom/client";
import { useState } from "react";
import { BindingProvider, useAction, useBinding } from "@n6k.io/ui";
import Layout from "../layout.tsx";

type Todo = { id: number; text: string; done: boolean };

function TodoApp() {
  const [todos, setTodos] = useBinding<Todo[]>("todos");
  const [addTodo, addState] = useAction<{ todos: Todo[] }>("add_todo");
  const [toggleTodo] = useAction<{ todos: Todo[] }>("toggle_todo");
  const [deleteTodo] = useAction<{ todos: Todo[] }>("delete_todo");
  const [text, setText] = useState("");

  const handleAdd = async () => {
    if (!text.trim()) return;
    const res = await addTodo({ text });
    if (res?.todos) setTodos(res.todos);
    setText("");
  };

  const handleToggle = async (id: number) => {
    const res = await toggleTodo({ id });
    if (res?.todos) setTodos(res.todos);
  };

  const handleDelete = async (id: number) => {
    const res = await deleteTodo({ id });
    if (res?.todos) setTodos(res.todos);
  };

  return (
    <div className="max-w-md mx-auto space-y-4">
      <h1 className="text-2xl font-bold">Todo</h1>

      <div className="flex gap-2">
        <input
          type="text"
          value={text}
          onChange={(e) => setText(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleAdd()}
          placeholder="What needs to be done?"
          className="flex-1 rounded border border-border bg-background px-3 py-2 text-sm"
        />
        <button
          onClick={handleAdd}
          disabled={addState.pending || !text.trim()}
          className="rounded bg-primary px-4 py-2 text-sm text-primary-foreground disabled:opacity-50"
        >
          {addState.pending ? "Adding..." : "Add"}
        </button>
      </div>

      {addState.error && (
        <p className="text-sm text-destructive">{addState.error}</p>
      )}

      <ul className="space-y-1">
        {(todos ?? []).map((todo) => (
          <li key={todo.id} className="flex items-center gap-2 rounded px-2 py-1 hover:bg-muted">
            <button
              onClick={() => handleToggle(todo.id)}
              className="h-5 w-5 shrink-0 rounded border border-border text-xs"
            >
              {todo.done ? "\u2713" : ""}
            </button>
            <span className={`flex-1 text-sm ${todo.done ? "line-through opacity-50" : ""}`}>
              {todo.text}
            </span>
            <button
              onClick={() => handleDelete(todo.id)}
              className="text-xs text-muted-foreground hover:text-destructive"
            >
              ×
            </button>
          </li>
        ))}
      </ul>

      {(todos ?? []).length === 0 && (
        <p className="text-sm text-muted-foreground">No todos yet.</p>
      )}
    </div>
  );
}

createRoot(document.getElementById("root")!).render(
  <BindingProvider defaults={{ todos: [{ id: 1, text: "Try the todo app", done: false }] }}>
    <Layout>
      <TodoApp />
    </Layout>
  </BindingProvider>
);
