import { queryOptions, createQuery } from "@tanstack/solid-query";
import { createFileRoute } from "@tanstack/solid-router";
import { For, Match, Switch } from "solid-js";

const todoQueryOptions = queryOptions({
  queryKey: ["todo"],
  queryFn: () => {
    console.log("Fetching todos...");
    return fetch("https://jsonplaceholder.typicode.com/todos").then((res) =>
      res.json(),
    );
  },
});

export const Route = createFileRoute("/todo")({
  component: RouteComponent,
  loader: ({ context }) =>
    context.queryClient.ensureQueryData(todoQueryOptions),
});

function RouteComponent() {
  const query = createQuery(() => todoQueryOptions);

  return (
    <div>
      <Switch fallback={<div>Loading...</div>}>
        <Match when={query.isError}>
          <div>Error: {query.error?.message}</div>
        </Match>
        <Match when={query.isLoading}>
          <div>Loading...</div>
        </Match>
        <Match when={query.data}>
          <For each={query.data}>{(item) => <TodoItem item={item} />}</For>
        </Match>
      </Switch>
    </div>
  );
}

interface TodoItemProps {
  item: {
    userId: number;
    id: number;
    title: string;
    completed: boolean;
  };
}

function TodoItem({ item }: TodoItemProps) {
  return (
    <div class="p-2">
      <div>{item.title}</div>
      <div>{item.completed ? "Completed" : "Pending"}</div>
    </div>
  );
}
