import { waitForElement, changeTags } from "../../requests/index.js";

export default class TagsComponent {
  element;
  constructor({ tags = [], bookid = null, article }) {
    this.tags = tags;
    this.article = article;
    this.bookid = bookid;
    this.isTextareaMode = false;
    this.render();
  }

  get template() {
    return `
        <h6 data-edit-tag class="main-book__tags_title mt-m">
            Теги
            <div class="pencil"></div>
        </h6>
      <div class="main-book__center main-book__tags d-fl mv-s">${this.getTags(
        this.tags
      )}</div>
      `;
  }
  getTags(tags) {
    return (tags || [])
      .map(({ id, name }) => {
        return `<a class="main-book__tag main-book__link" data-tag=${id}>#${name}</a>`;
      })
      .join("");
  }

  getTextarea(tags) {
    return `
      <textarea class="main-book__textarea" data-area>${(tags || [])
        .map(({ name }) => name)
        .join(" ")}</textarea>
    `;
  }

  initialize() {
    this.initEventListeners();
  }

  initEventListeners() {
    const tagsEditorListener = this.article.querySelector(
      ".main-book__tags_title"
    );

    tagsEditorListener.addEventListener("click", () => {
      const tagsWrapper = this.article.querySelector(".main-book__tags");

      if (!this.isTextareaMode) {
        tagsWrapper.innerHTML = this.getTextarea(this.tags);
        this.article.querySelector(".main-book__textarea").focus();
        this.isTextareaMode = true;
      }
    });

    this.article.addEventListener("keypress", (event) => {
      if (event.key === "Enter") {
        if (this.isTextareaMode) {
          this.closeTextarea();
        }
      }
    });

    document.addEventListener("outside-click", async () => {
      if (this.isTextareaMode) {
        this.closeTextarea();
      }
    });
  }

  async closeTextarea() {
    const tagsWrapper = this.article.querySelector(".main-book__tags");
    const area = this.article.querySelector(".main-book__textarea");

    const tags = area.value
      .split(" ")
      .map((item) => item.trim())
      .filter((i) => i);
    if (!!(tags || []).length > 0) {
      await this.setTags({ bookid: this.bookid, tags });
    }
    tagsWrapper.innerHTML = this.getTags(this.tags);
    this.isTextareaMode = false;
  }

  async waitRendered() {
    await waitForElement(".main-book__tags");
    this.initialize();
  }

  async render() {
    this.element = document.createElement("div");
    this.element.innerHTML = this.template;
    await this.waitRendered();
  }

  async setTags({ bookid, tags }) {
    document.body.classList.add("blur", "spinner");
    const newTags = await changeTags({ bookid, tags });
    this.tags = newTags;
    document.body.classList.remove("spinner");
  }
}
