import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { createFileRoute } from "@tanstack/react-router";
import { Loader2, Trash2 } from "lucide-react";
import { useState } from "react";

{{#if (eq backend "convex")}}
import { useMutation, useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api";
import type { Id } from "@{{projectName}}/backend/convex/_generated/dataModel";
{{else}}
  {{#if (eq api "orpc")}}
  import { orpc } from "@/utils/orpc";
  {{/if}}
  {{#if (eq api "trpc")}}
  import { trpc } from "@/utils/trpc";
  {{/if}}
import { useMutation, useQuery } from "@tanstack/react-query";
{{/if}}

export const Route = createFileRoute("/todos")({
  component: TodosRoute,
});

function TodosRoute() {
  const [newTodoText, setNewTodoText] = useState("");

  {{#if (eq backend "convex")}}
  const todos = useQuery(api.todos.getAll);
  const createTodo = useMutation(api.todos.create);
  const toggleTodo = useMutation(api.todos.toggle);
  const deleteTodo = useMutation(api.todos.deleteTodo);

  const handleAddTodo = async (e: React.FormEvent) => {
    e.preventDefault();
    const text = newTodoText.trim();
    if (!text) return;
    await createTodo({ text });
    setNewTodoText("");
  };

  const handleToggleTodo = (id: Id<"todos">, currentCompleted: boolean) => {
    toggleTodo({ id, completed: !currentCompleted });
  };

  const handleDeleteTodo = (id: Id<"todos">) => {
    deleteTodo({ id });
  };
  {{else}}
    {{#if (eq api "orpc")}}
    const todos = useQuery(orpc.todo.getAll.queryOptions());
    const createMutation = useMutation(
      orpc.todo.create.mutationOptions({
        onSuccess: () => {
          todos.refetch();
          setNewTodoText("");
        },
      }),
    );
    const toggleMutation = useMutation(
      orpc.todo.toggle.mutationOptions({
        onSuccess: () => { todos.refetch() },
      }),
    );
    const deleteMutation = useMutation(
      orpc.todo.delete.mutationOptions({
        onSuccess: () => { todos.refetch() },
      }),
    );
    {{/if}}
    {{#if (eq api "trpc")}}
    const todos = useQuery(trpc.todo.getAll.queryOptions());
    const createMutation = useMutation(
      trpc.todo.create.mutationOptions({
        onSuccess: () => {
          todos.refetch();
          setNewTodoText("");
        },
      }),
    );
    const toggleMutation = useMutation(
      trpc.todo.toggle.mutationOptions({
        onSuccess: () => { todos.refetch() },
      }),
    );
    const deleteMutation = useMutation(
      trpc.todo.delete.mutationOptions({
        onSuccess: () => { todos.refetch() },
      }),
    );
    {{/if}}

  const handleAddTodo = (e: React.FormEvent) => {
    e.preventDefault();
    if (newTodoText.trim()) {
      createMutation.mutate({ text: newTodoText });
    }
  };

  const handleToggleTodo = (id: number, completed: boolean) => {
    toggleMutation.mutate({ id, completed: !completed });
  };

  const handleDeleteTodo = (id: number) => {
    deleteMutation.mutate({ id });
  };
  {{/if}}

  return (
    <div className="mx-auto w-full max-w-md py-10">
      <Card>
        <CardHeader>
          <CardTitle>Todo List</CardTitle>
          <CardDescription>Manage your tasks efficiently</CardDescription>
        </CardHeader>
        <CardContent>
          <form
            onSubmit={handleAddTodo}
            className="mb-6 flex items-center space-x-2"
          >
            <Input
              value={newTodoText}
              onChange={(e) => setNewTodoText(e.target.value)}
              placeholder="Add a new task..."
              {{#if (eq backend "convex")}}
              {{else}}
              disabled={createMutation.isPending}
              {{/if}}
            />
            <Button
              type="submit"
              {{#if (eq backend "convex")}}
              disabled={!newTodoText.trim()}
              {{else}}
              disabled={createMutation.isPending || !newTodoText.trim()}
              {{/if}}
            >
              {{#if (eq backend "convex")}}
              Add
              {{else}}
                {createMutation.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  "Add"
                )}
              {{/if}}
            </Button>
          </form>

          {{#if (eq backend "convex")}}
            {todos === undefined ? (
              <div className="flex justify-center py-4">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : todos.length === 0 ? (
              <p className="py-4 text-center">No todos yet. Add one above!</p>
            ) : (
              <ul className="space-y-2">
                {todos.map((todo) => (
                  <li
                    key={todo._id}
                    className="flex items-center justify-between rounded-md border p-2"
                  >
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        checked={todo.completed}
                        onCheckedChange={() =>
                          handleToggleTodo(todo._id, todo.completed)
                        }
                        id={`todo-${todo._id}`}
                      />
                      <label
                        htmlFor={`todo-${todo._id}`}
                        className={`${todo.completed ? "line-through text-muted-foreground" : ""}`}
                      >
                        {todo.text}
                      </label>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleDeleteTodo(todo._id)}
                      aria-label="Delete todo"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          {{else}}
            {todos.isLoading ? (
              <div className="flex justify-center py-4">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : todos.data?.length === 0 ? (
              <p className="py-4 text-center">
                No todos yet. Add one above!
              </p>
            ) : (
              <ul className="space-y-2">
                {todos.data?.map((todo) => (
                  <li
                    key={todo.id}
                    className="flex items-center justify-between rounded-md border p-2"
                  >
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        checked={todo.completed}
                        onCheckedChange={() =>
                          handleToggleTodo(todo.id, todo.completed)
                        }
                        id={`todo-${todo.id}`}
                      />
                      <label
                        htmlFor={`todo-${todo.id}`}
                        className={`${todo.completed ? "line-through" : ""}`}
                      >
                        {todo.text}
                      </label>
                    </div>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleDeleteTodo(todo.id)}
                      aria-label="Delete todo"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </li>
                ))}
              </ul>
            )}
          {{/if}}
        </CardContent>
      </Card>
    </div>
  );
}
