import {
  type Component,
  createResource,
  createSignal,
  createEffect,
} from "solid-js";
import "./BlockedSite.css";

import { TODOS_REPO_KEY } from "@/utils/proxy-service-keys";
import type { Todo } from "@/utils/types";
import { createProxyService } from "@webext-core/proxy-service";
import { v4 as uuidv4 } from "uuid";

const todosRepo = createProxyService(TODOS_REPO_KEY);

export const Todo: Component = (props) => {
  const [rawTodos, { refetch }] = createResource(todosRepo.getAll, []);
  const [todos, setTodos] = createSignal([]);
  const [inputNewTodo, setInputNewTodo] = createSignal("");

  createEffect(async () => {
    const allTodos = rawTodos();
    if (!allTodos) {
      return;
    }
    console.log("OI");
    const filteredTodos = allTodos.filter(
      (todo: Todo) =>
        (props.showCompleted && todo.completed) ||
        (props.showOnlyCompleted && todo.completed) ||
        (!props.showOnlyCompleted && !todo.completed),
    );
    setTodos(filteredTodos);
  });

  const createTodo = async () => {
    const name = inputNewTodo();
    if (!name) return;
    if (!name.trim()) return;
    const generateTodoId = uuidv4();
    await todosRepo.insert({
      id: generateTodoId,
      name: name,
      completed: false,
    });
    setInputNewTodo("");
    await refetch();
  };

  const updateTodo = async (todo: Todo, isCompleted: boolean) => {
    todo.completed = isCompleted;
    await todosRepo.update(todo);
    await refetch();
  };

  const deleteTodo = async (todo: Todo) => {
    await todosRepo.delete(todo);
    await refetch();
  };

  const clearAllCompletedTodo = async () => {
    const allTodos = await todosRepo.getAll();
    const completedTodos = allTodos.filter((todo) => todo.completed);
    const deletePromises = completedTodos.map((todo) => todosRepo.delete(todo));
    await Promise.all(deletePromises);
    refetch();
  };

  return (
    <>
      <div class="container">
        {props.showOnlyCompleted ? (
          <h2>[completed todos]</h2>
        ) : (
          <h2>[todos]</h2>
        )}
        {props.showInput && (
          <div class="form-input">
            <input
              placeholder="playing skateboard at 5am"
              onKeyDown={(e) => {
                // key code 13 is enter
                if (e.keyCode === 13) {
                  createTodo();
                }
              }}
              onInput={(e) => setInputNewTodo(e.currentTarget.value)}
              type="input"
            />
            <button onClick={() => createTodo()}>[add todo]</button>
          </div>
        )}
        {props.showClearAllTodo && (
          <div>
            <button onClick={() => clearAllCompletedTodo()}>
              [clear all completed todos]
            </button>
          </div>
        )}
        <br />
        <For each={todos()}>
          {(todo) => {
            return (
              <li>
                <label>
                  <input
                    type="checkbox"
                    checked={todo.completed}
                    onChange={(e) => updateTodo(todo, e.currentTarget.checked)}
                  />
                  {todo.name}
                  {props.hoverShowDeleteButton && (
                    <button
                      class="button-delete"
                      onClick={() => deleteTodo(todo)}
                    >
                      x
                    </button>
                  )}
                </label>
              </li>
            );
          }}
        </For>
      </div>
    </>
  );
};
