import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IMessageTemplateModel } from '@fleio-api/message-templates/model/message-template.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { of } from 'rxjs';
import { MessageTemplatesApiService } from '@fleio-api/message-templates/message-templates-api.service';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { IMessageTemplateCreateOptionsModel } from '@fleio-api/message-templates/model/message-template-create-options';
import { ThemingService } from '@shared/ui/theming/theming.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Component({
  selector: 'app-message-template-create-form',
  templateUrl: './message-template-create-form.component.html',
  styleUrls: ['./message-template-create-form.component.scss']
})
export class MessageTemplateCreateFormComponent extends DetailsFormBase<IMessageTemplateModel> implements OnInit {
  public createOptions: IMessageTemplateCreateOptionsModel;
  templateForm = this.formBuilder.group({
    target: [null, Validators.required],
    target_category: [''],
    category: [null, Validators.required],
    title: [null, Validators.required],
    name: [null, Validators.required],
    content: [null, Validators.required],
  });
  tinyMCEOptions = null;
  selectedCategory = null;
  fieldRequiredTxt = $localize`This field is required!`;
  clickToCopyTooltip = $localize`Click to copy`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private messageTemplatesApiService: MessageTemplatesApiService,
    private router: Router,
    private config: ConfigService,
    private themingService: ThemingService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit(): void {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveTemplate();
      this.createOptions = this.objectController.additionalObjects.createOptions;
      this.templateForm.controls.category.valueChanges.subscribe(value => {
        for (const category of this.createOptions.categories) {
          if (value === category.id) {
            this.selectedCategory = category;
            break;
          }
        }
      });
    }
    if (this.config.current) {
      this.tinyMCEOptions = this.themingService.getTinyMceOptions();
    }
  }

  clickVariable(item: string) {
    const textArea = document.createElement('textarea');
    textArea.value = item;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('Copy');
    textArea.remove();
    this.notificationService.showMessage($localize`Successfully copied`);
  }

  handleTinyKeyDown(event: any) {
    if (event && event.event && event.event.ctrlKey && event.event.keyCode === 13) {
      event.event.preventDefault();
      this.saveTemplate();
    }
  }

  saveTemplate() {
    const value = this.templateForm.value as IMessageTemplateModel;

    this.createOrUpdate(this.messageTemplatesApiService, value).subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPanelUrl('settings/message-templates')
      ).catch(() => {
      });
    });

    return of(null);
  }

}
