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

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

const blockedSitesRepo = createProxyService(BLOCKED_SITES_REPO_KEY);

export const BlockedSite: Component = (props) => {
  const [blockedSites, { refetch }] = createResource(blockedSitesRepo.getAll);
  const [inputNewSite, setInputNewSite] = createSignal("");

  const createBlockedSite = async () => {
    const url = inputNewSite();
    if (!url) return;
    if (!url.trim()) return;
    const generateTodoId = uuidv4();
    await blockedSitesRepo.insert({
      id: generateTodoId,
      url: url,
      blocked: true,
    });
    setInputNewSite("");
    await refetch();
  };

  const updateBlockedSite = async (
    blockedSite: BlockedSite,
    isBlocked: boolean,
  ) => {
    blockedSite.blocked = isBlocked;
    await blockedSitesRepo.update(blockedSite);
    await refetch();
  };

  const deleteBlockedSite = async (blockedSite: BlockedSite) => {
    await blockedSitesRepo.delete(blockedSite);
    await refetch();
  };

  return (
    <>
      <div class="container">
        <h2>[blocked sites]</h2>
        <div class="form-input">
          <input
            placeholder="ba-ka.org"
            onKeyDown={(e) => {
              // key code 13 is enter
              if (e.keyCode === 13) {
                createBlockedSite();
              }
            }}
            onInput={(e) => setInputNewSite(e.currentTarget.value)}
            type="input"
          />
          <button onClick={() => createBlockedSite()}>[add site]</button>
        </div>
        <br />
        <For each={blockedSites()}>
          {(blockedSite) => {
            return (
              <li>
                <label>
                  <input
                    type="checkbox"
                    checked={blockedSite.blocked}
                    onChange={(e) =>
                      updateBlockedSite(blockedSite, e.currentTarget.checked)
                    }
                  />
                  {blockedSite.url}
                  <button
                    class="button-delete"
                    onClick={() => deleteBlockedSite(blockedSite)}
                  >
                    x
                  </button>
                </label>
              </li>
            );
          }}
        </For>
      </div>
    </>
  );
};
