
import { Component, h, Element, State, Host, Prop } from "@stencil/core";
import { LogClickEventActionCreatorPayload, loadGenericAnalyticsActions } from '@coveo/headless';
import { resultContext, Bindings, initializeBindings } from "@coveo/atomic";

import {
  Result
} from "@coveo/headless";

@Component({
  tag: "faq-popup-component",
  styleUrl: "faq-popup-component.css",
  shadow: true,
})
export class FaqPopupComponent {
  @Prop() origin?: string;
  private bindings?: Bindings;
  private modalElement?: any;

  // The Headless result object to be resolved from the parent atomic-result component.
  @State() private result?: Result;
  @Element() private host!: Element;

  // We recommended fetching the result context using the `connectedCallback` lifecycle method
  // with async/await. Using `componentWillLoad` will hang the parent `atomic-search-interface` initialization.
  public async connectedCallback() {

    try {
      this.bindings = await initializeBindings(this.host);
      this.result = await resultContext(this.host);
      this.modalElement = this.bindings?.interfaceElement.querySelector('#faq-modal');

      if (this.result && localStorage.getItem(`visited-${this.result.title}`)) {

        this.host.classList.add('visited-title');
      }
    } catch (error) {
      console.error(error);
      this.host.remove();
    }
  }



  private openFAQModal(result: Result) {
    if(this.bindings){
      const { logClickEvent } = loadGenericAnalyticsActions (this.bindings.engine);
      const logClickPayload : LogClickEventActionCreatorPayload= { 
        evt: 'documentQuickview',
        result: result,
      }
      this.bindings.engine.dispatch(logClickEvent(logClickPayload))
    }
    this.modalElement.source = this.host; 
    // Get the body slot
    const bodySlot = this.modalElement.querySelector('[slot=body]');

    // Clear any existing content
    bodySlot.innerHTML = '';

    const tableEl = document.createElement('table');

    const questionElement = document.createElement("tr");
    questionElement.className = "question-row";
    questionElement.innerHTML = '<td>Question: <a href="https://anheuserbuschinbev.sharepoint.com" autofocus="true" style="display:none;"></a></td> <td>' + (this.result?.title || '') + '</td>'
        +'<div id="faq-modal-close-button"><svg width="48" height="49" viewBox="0 0 48 49" fill="black" xmlns="http://www.w3.org/2000/svg"><rect y="0.5" width="48" height="48" rx="24" fill="white"/><path fill-rule="evenodd" clip-rule="evenodd" d="M22.5382 24.5L15 16.9618L16.4618 15.5L24 23.0382L31.5382 15.5L33 16.9618L25.4618 24.5L33 32.0382L31.5382 33.5L24 25.9618L16.4618 33.5L15 32.0382L22.5382 24.5Z" fill="#17171A"/></svg></div>';

    tableEl.appendChild(questionElement);

    const answerElement = document.createElement('tr');
    
    // Create the answer title element and set its text
    const answerTitleElement = document.createElement('td');
    answerTitleElement.innerText = 'Answer:';
    answerElement.appendChild(answerTitleElement);

    // Create a new element to contain the answer content
    const answerContentElement = document.createElement('td');
    if(this.result?.raw?.answer) {
      let value = this.result?.raw?.answer as string;
      try {
        var els = new DOMParser().parseFromString(value,'text/html');
        var html = '';
        Array.from(els.children).forEach(el => {
          el.querySelectorAll('a').forEach(a => {
            if (a.href.startsWith(window.location.origin) && a.href.indexOf('/sites/') > -1) {
              a.href = a.href.replace(window.location.origin, 'https://anheuserbuschinbev.sharepoint.com');
            }
            if (a.href.startsWith(window.location.origin) && a.href.match(/:.:\/./)) {
              a.href = a.href.replace(window.location.origin, 'https://anheuserbuschinbev.sharepoint.com');
            }
          });
          el.querySelectorAll('img').forEach(a => {
            if (a.src.startsWith(window.location.origin) && a.src.indexOf('/sites/') > -1) {
              a.src = a.src.replace(window.location.origin, 'https://anheuserbuschinbev.sharepoint.com');
            }
            if (a.src.startsWith(window.location.origin) && a.src.match(/:.:\/./)) {
              a.src = a.src.replace(window.location.origin, 'https://anheuserbuschinbev.sharepoint.com');
            }
          });
          html = html + el.querySelector('body')?.innerHTML;
        });
        answerContentElement.innerHTML = html;
      }
      catch (e) {
        console.log(e);
        answerContentElement.innerHTML = value;
      }
    }
    

    // Append the answer content element to the answer element
    answerElement.appendChild(answerContentElement);

    // Now, the answer element has the title and the content properly appended

    tableEl.appendChild(answerElement);


    if(this.result?.raw.category) {
      const categoryElement = document.createElement("tr");
      categoryElement.innerHTML = '<td> Category: </td><td>'+ this.result.raw.category + '</td>';
      tableEl.appendChild(categoryElement);
    }

    if(this.result?.raw.newmoreinfo) {
      const linkElement = document.createElement("tr");
      const linkUrl = this.result.raw.newmoreinfo;
      linkElement.innerHTML = '<td> Link: </td><td> <a href="'+linkUrl+'" target="_blank">'+linkUrl+'</a> </td>';
      tableEl.appendChild(linkElement);
    }

    // Create and append the category element
    /*const categoryElement = document.createElement('div');
    categoryElement.innerHTML = 'Category: ' + (this.result?.raw.category || '');
    bodySlot.appendChild(categoryElement);




    const linkElement = document.createElement('div');
    const linkUrl = this.result?.raw.newmoreinfo || '';
    linkElement.innerHTML = `Link: <a href="${linkUrl}" target="_blank">${linkUrl}</a>`;
    bodySlot.appendChild(linkElement);*/

    bodySlot.appendChild(tableEl);

    this.modalElement.querySelector('#faq-modal-close-button').addEventListener('click', this.closeFAQModal);
    this.modalElement.setAttribute('is-open', 'true');

    if (this.result) {
      localStorage.setItem(`visited-${this.result.title}`, 'true');
    }

    // Add the class to change color
    this.host.classList.add('visited-title');

  }
  private closeFAQModal: Function = () => {
    this.modalElement.setAttribute('is-open', 'false');
    this.modalElement.querySelector('#btn-done').removeEventListener('click', this.closeFAQModal);
  }
  public render() {
    if (!this.result) {
      return;
    }
    const cssCondition = this.origin === 'searchResult' ? 'search-css' : '';
    return (
      <Host className={`clickable-host ${cssCondition}`}  onClick={() => this.openFAQModal(this.result!)}>
        {this.result.title}
      </Host>
    );
  }
}
