import { debounce } from "../artists.js";
import { kemonoAPI } from "@wp/api";
import { freesites, paysites } from "@wp/utils";
import { BANNERS_PREPEND, ICONS_PREPEND } from "@wp/env/env-vars";

/**
 * @type {Array}
 */
let ALL_CREATORS;

export function newLinkedAccountPage() {
  document.getElementById("service").addEventListener("input", debounce(testUser, 300))
  document.getElementById("creator_name").addEventListener("input", debounce(testUser, 300))
  document.getElementById("reason").addEventListener("input", debounce(validateReason, 300))
  testUser();
}

function validateReason() {
  let reason = document.getElementById("reason");

  if (reason.value.length > 140) {
    reason.title = "Too long (140 max)";
    reason.classList.add("invalid");
  } else {
    reason.title = "";
    reason.classList.remove("invalid");
  }
}

async function testUser() {
  if (ALL_CREATORS === undefined) {
    ALL_CREATORS = await kemonoAPI.api.creators();
  }

  const CURRENT_ARTIST_ID = document.querySelector("meta[name='id']").content;
  const CURRENT_ARTIST_SERVICE = document.querySelector("meta[name='service']").content;
  let service = document.getElementById("service").value;
  let creatorName = document.getElementById("creator_name").value.toLowerCase();
  let button = document.getElementById("submit");
  let resultBox = document.getElementById("lookup-result");

  button.disabled = true;

  let items = ALL_CREATORS.filter(item => {
    console.log(item);
    return !(item.service === CURRENT_ARTIST_SERVICE && item.id === CURRENT_ARTIST_ID)
         && (creatorName? item.name.toLowerCase().includes(creatorName) : true)
         && (service !== "all"? item.service === service : true);
  }).slice(0, 20).map(createCard);
  console.log(items);
  resultBox.replaceChildren.apply(resultBox, items);
}

function createCard({id, name, service, indexed, updated, favorited}) {
  // would like to use initUserCardFromScratch here, but it doesn't work.
  // why would components be reuseable, after all?

  // so I'll just recreate the entire function here!
  let updatedDate;

  if (updated || indexed) {
    updatedDate = new Date((updated || indexed) * 1000).toISOString();
  }

  let profileIcon = freesites.kemono.user.icon(service, id);
  let profileBanner = freesites.kemono.user.banner(service, id);

  profileIcon = ICONS_PREPEND + profileIcon;
  profileBanner = BANNERS_PREPEND + profileBanner;

  let div = document.createElement("div");
  div.innerHTML = `
  <a href="/${service}/user/${id}" class="user-card" style="background-image: linear-gradient(rgb(0 0 0 / 50%), rgb(0 0 0 / 80%)), url(&quot;${profileBanner}&quot;)">
    <div class="user-card__icon">
      <div class="user-card__user-icon">
        <span class="fancy-image">
          <picture class="fancy-image__picture">
            <img class="fancy-image__image" src="${profileIcon}" srcset="${profileIcon}" loading="lazy" alt="">
          </picture>
        </span>
      </div>
    </div>

    <div class="user-card__info">
      <div class="user-card__service" style="background-color: ${paysites[service].color}">
        ${paysites[service].title}
      </div>

      <div class="user-card__name">
        ${name}
      </div>

      <div class="user-card__updated">
        <time class="timestamp" datetime="${updatedDate}">
          ${updatedDate}
        </time>
      </div>
    </div>
  </a>
  `;
  div.addEventListener("click", (e) => {
    e.preventDefault();

    Array.from(document.querySelectorAll(".user-card.selected")).forEach(item => item.classList.remove("selected"));

    div.children[0].classList.add("selected");
    document.querySelector("#new_link_form #creator").value = `${service}/${id}`;
    document.querySelector("#new_link_form #submit").disabled = false;
  });
  return div;
}
