import { Component, OnInit, ViewChild, ElementRef, OnDestroy } from '@angular/core';
import grapesjs from 'grapesjs';
import presetWebpage from 'grapesjs-preset-webpage';

const editor = grapesjs.init({
  container: '#editor',
  plugins: [presetWebpage],
});


import { COMMON_CSS } from './common-css';

@Component({
  selector: 'app-wire-frame-edit',
  templateUrl: './wire-frame-edit.component.html',
  styleUrls: ['./wire-frame-edit.component.scss'] // use your CSS here
})
export class WireFrameEditComponent implements OnInit, OnDestroy {
  @ViewChild('gjsContainer', { static: false }) gjsContainer!: ElementRef<HTMLDivElement>;

  mapOfAllHtmlPages: { [key: string]: string } = {};
  pageKeys: string[] = [];
  currentPageIndex: number = 0;
  currentPageName: string = '';
  currentPageHtml: string = '';
  totalPages: number = 0;

  sidebarOpen = true;
  private editor: any = null;

  ngOnInit(): void {
    this.mapOfAllHtmlPages = JSON.parse(localStorage.getItem('mapOfHtml') || '{}');
    this.pageKeys = Object.keys(this.mapOfAllHtmlPages);
    this.totalPages = this.pageKeys.length;
    if (this.totalPages > 0) {
      this.loadPage(0);
    }
  }

  ngAfterViewInit() {
    // Initialize GrapesJS after view is ready
    if (this.gjsContainer && this.currentPageHtml) {
      this.initGrapesJs();
    }
  }

  ngOnDestroy() {
    this.editor?.destroy();
  }

  loadPage(index: number): void {
    if (index >= 0 && index < this.totalPages) {
      this.currentPageIndex = index;
      this.currentPageName = this.pageKeys[index];
      this.currentPageHtml = this.mapOfAllHtmlPages[this.currentPageName];
      // If GrapesJS already initialized, update its content
      if (this.editor) {
        this.editor.setComponents(this.currentPageHtml, { keepScripts: true });
      }
    }
  }

  nextPage(): void {
    if (this.currentPageIndex < this.totalPages - 1) {
      this.loadPage(this.currentPageIndex + 1);
    }
  }

  prevPage(): void {
    if (this.currentPageIndex > 0) {
      this.loadPage(this.currentPageIndex - 1);
    }
  }

  hasNextPage(): boolean {
    return this.currentPageIndex < this.totalPages - 1;
  }

  hasPrevPage(): boolean {
    return this.currentPageIndex > 0;
  }

  getCurrentPageNumber(): number {
    return this.currentPageIndex + 1;
  }

  toggleSidebar() {
    this.sidebarOpen = !this.sidebarOpen;
  }

  downloadHtml() {
    const blob = new Blob([this.currentPageHtml], { type: 'text/html' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `${this.currentPageName || 'exported-page'}.html`;
    a.click();
    URL.revokeObjectURL(a.href);
  }

  private initGrapesJs() {
    // If already initialized, destroy and re-init
    if (this.editor) {
      this.editor.destroy();
    }
    this.editor = grapesjs.init({
      container: this.gjsContainer.nativeElement,
      fromElement: false,
      storageManager: false,
      plugins: ['gjs-preset-webpage'],
      allowScripts: 1,
    } as any);

    this.editor.setComponents(this.currentPageHtml, { keepScripts: true });

    this.editor.on('component:update', this.updateCurrentPageHtml.bind(this));
    this.editor.on('style:change', this.updateCurrentPageHtml.bind(this));
  }

  private updateCurrentPageHtml() {
    if (!this.editor) return;
    const html = this.editor.getHtml();
    const css = this.editor.getCss();
    this.currentPageHtml = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>${this.currentPageName}</title>
  <style>${css }</style>
  <style>${COMMON_CSS }</style>

</head>
<body>
  ${html}
</body>
</html>
    `;
    // Optionally, update your map and localStorage here if you want autosave
    // this.mapOfAllHtmlPages[this.currentPageName] = this.currentPageHtml;
    // localStorage.setItem('mapOfHtml', JSON.stringify(this.mapOfAllHtmlPages));
  }
}
