import { Component, inject, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';

import SharedModule from 'app/shared/shared.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { EditorModule } from '@tinymce/tinymce-angular';

import { ResilientBaseComponent } from 'app/resilient/resilient-base/resilient-base.component';

import { ContentPageType } from 'app/entities/enumerations/content-page-type.model';
import { IContentPage } from '../content-page.model';
import { ContentPageService } from '../service/content-page.service';
import { ContentPageFormService, ContentPageFormGroup } from './content-page-form.service';
import { Editor } from 'content/tinymce/tinymce';

@Component({
  standalone: true,
  selector: 'jhi-content-page-update',
  templateUrl: './content-page-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule, EditorModule],
})
export class ContentPageUpdateComponent extends ResilientBaseComponent implements OnInit {
  isSaving = false;
  contentPage: IContentPage | null = null;
  contentPageTypeValues = Object.keys(ContentPageType);

  /* TinyMCE Html Editor config options */
  editorConfig = {
    height: 500,
    menubar: false,
    image_dimensions: true, // disables the width/height input fields
    automatic_uploads: false,
    setup: (editor: any) => {
      // Clean up default width/height if they were added automatically
      editor.on('BeforeSetContent', (e: any) => {
        if (e.content.includes('<img')) {
          // Remove width/height only if they are exactly the defaults (e.g., 300, 150)
          e.content = e.content.replace(/width="300"/g, '');
          e.content = e.content.replace(/height="150"/g, '');
        }
      });
    },
    plugins: [
      'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview', 'anchor', 
      'searchreplace', 'visualblocks', 'code', 'fullscreen', 
      'insertdatetime', 'media', 'table'
    ],
    toolbar: 
      'undo redo | paste | ' + 
      'bold italic underline strikethrough subscript superscript | forecolor backcolor | ' + 
      'alignleft aligncenter alignright alignjustify | ' + 
      'bullist numlist outdent indent | ' +
      'link image | table | removeformat | code',
    content_style: `
      body { font-family:Helvetica,Arial,sans-serif; font-size:14px }
      table, th, td { border: 1px solid #ccc; border-collapse: collapse; padding: 5px; }
    `,
    table_toolbar: 'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | ' +
      'tableinsertcolbefore tableinsertcolafter tabledeletecol | tablecellprops',
    // Use local TinyMCE instance
    base_url: '/content/tinymce/', // Base URL for the assets
    suffix: '.min',       // 👈 tells it to use .min.js files
    minSuffix: '.min',    // 👈 same here
    tinymceScriptSrc: '/content/tinymce/tinymce.min.js',
    // Set licence to gpl, to remove the evaluation message from browser console
    license_key: 'gpl'
  };

  protected contentPageService = inject(ContentPageService);
  protected contentPageFormService = inject(ContentPageFormService);
  protected activatedRoute = inject(ActivatedRoute);

  // eslint-disable-next-line @typescript-eslint/member-ordering
  editForm: ContentPageFormGroup = this.contentPageFormService.createContentPageFormGroup();

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ contentPage }) => {
      this.contentPage = contentPage;
      if (contentPage) {
        this.updateForm(contentPage);
      }
    });
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving = true;
    const contentPage = this.contentPageFormService.getContentPage(this.editForm);
    if (contentPage.id !== null) {
      this.subscribeToSaveResponse(this.contentPageService.update(contentPage));
    } else {
      // TODO : Throw exception. Creation is NOT allowed
      this.subscribeToSaveResponse(this.contentPageService.create(contentPage));
    }
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IContentPage>>): void {
    result.pipe(finalize(() => this.onSaveFinalize())).subscribe({
      next: () => this.onSaveSuccess(),
      error: () => this.onSaveError(),
    });
  }

  protected onSaveSuccess(): void {
    this.previousState();
  }

  protected onSaveError(): void {
    // Api for inheritance.
  }

  protected onSaveFinalize(): void {
    this.isSaving = false;
  }

  protected updateForm(contentPage: IContentPage): void {
    this.contentPage = contentPage;
    this.contentPageFormService.resetForm(this.editForm, contentPage);
  }
}
