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 `<div class="main-book_edit">
    ${
      !(this.tags && this.tags.length)
        ? this.getTitle()
        : this.getTags(this.tags)
    }
    </div>`;
  }

  getTitle() {
    return `<h6 data-tags-editor class="main-book__tags_title mt-s mb-m">
              Добавить теги
              <div class="main-book__pencil pencil"></div>
            </h6> `;
  }

  getTags(tags) {
    return `<div class="main-book__center main-book__tags d-fl mt-s mb-m">
    ${(tags || [])
      .map(({ id, name }) => {
        return `<a class="main-book__tag main-book__link" data-tag=${id}>#${name}</a>`;
      })
      .join("")}
    <div data-tags-editor class="pencil"></div></div>`;
  }

  getTextarea(tags) {
    return `
      <textarea data-tags-editor placeholder="Редактировать поле" class="main-book__textarea" data-area>${(
        tags || []
      )
        .map(({ name }) => name)
        .join(" ")}</textarea>
    `;
  }

  initialize() {
    this.initEventListeners();
  }

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

    tagsEditorListener.addEventListener("click", () => {
      if (!this.isTextareaMode) {
        const tagsWrapper = this.article.querySelector(".main-book_edit");
        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("tag-outside-click", async () => {
      if (this.isTextareaMode) {
        this.closeTextarea();
      }
    });
  }

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

    const tags = area.value
      .split(" ")
      .map((item) => item.trim())
      .filter((i) => i);

    if (
      this.tags?.length !== tags?.length ||
      (this.tags || []).some(({ name }, index) => name !== tags[index])
    ) {
      await this.setTags({ bookid: this.bookid, tags });
    }

    if (!!(tags || []).length > 0) {
      tagsWrapper.innerHTML = this.getTags(this.tags);
    } else {
      tagsWrapper.innerHTML = this.getTitle();
    }
    this.isTextareaMode = false;
  }

  async waitRendered() {
    await waitForElement(".main-book_edit");
    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");
  }
}
