import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { FormGroup, FormBuilder, NgForm, FormsModule } from '@angular/forms';
import { HttpHeaders } from '@angular/common/http';
import { takeUntil } from 'rxjs';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../../shared/class/unsub.class';
import { AdminService } from '../../../../shared/services/admin/admin.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { ImageUploadComponent } from '../../../../shared/common/includes/image-upload/image-upload.component';

@Component({
  selector: 'app-call-to-action',
  templateUrl: './call-to-action.component.html',
  styleUrls: ['./call-to-action.component.scss'],
  standalone : true,
  imports: [AdminPageHeaderComponent, TranslatePipes, ImageUploadComponent, FormsModule]
})
export class CallToActionComponent extends Unsub implements OnInit {
  callToAction;loading = true;
  public sendingResponse: { [key: string]: boolean } = {};
  form: FormGroup;
  setting: any;
  constructor(
    private adminService: AdminService,
    private toastr: ToastrService,
    public fb: FormBuilder,
    private translate: TranslatePipe,
    loaderService: LoaderService
  ) {
    /**
    * This code calls the constructor of the parent class in a subclass. 
    * The super() function is used to initialize the parent class and allows access to its properties and methods. 
    * By calling  super(), the subclass can inherit and use the functionality of the parent class.
    **/
    super(loaderService);
    this.loaderService.showLoader();
    this.adminService
      .callToAction()
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.callToAction = res.callaction;
          this.setting = res.setting?.original;
          this.loaderService.hideLoader();
          this.loading = false;
        },
        error : ()=> this.loaderService.hideLoader()
      });

    this.form = this.fb.group({
      image: null,
    });
  }

  ngOnInit(): void { }

  updateCallToAction(ngForm: NgForm, buttonId) {
    if (ngForm.valid) {

      const formData: any = new FormData();
      for (const key of Object.keys(ngForm.value)) {
        if (key != 'callcheck') {
          formData.append(key, ngForm.value[key]);
        }
      }
      // formData.append('image', this.form.controls['image'].value);
      if (ngForm.value.callcheck == true || ngForm.value.callcheck == 'on') {
        formData.append('callcheck', ngForm.value.callcheck);
      }
      for (let i = 0; i < this.ticketName?.length; i++) {
        formData.append('image', this.ticketName[i]);
      }
      if(this.calltoactionRemoved){
        formData.append('calltoactionRemoved', this.calltoactionRemoved)
      }


      const httpOptions = {
        headers: new HttpHeaders({
          Accept: 'application/json',
        }),
      };
      this.sendingResponse[buttonId] = true;

      this.adminService
        .callToActionUpdate(formData, httpOptions)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            if (res.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.form.reset({});
            }
            if (res.error) {
              this.toastr.error(this.translate.transform(res.error.errors.message));
            }
          },
          error: () => {
             this.sendingResponse[buttonId] = false;
          },
        });
    }
  }

  ticketName: any[] = [];
  calltoactionRemoved: any[] = [];

  onImageUploaded(value) {
    this.ticketName = value.ticketName;
    if (value.mediaremoveIds) {
      value.mediaremoveIds.forEach(e => this.calltoactionRemoved.push(e.id))
    }
  }
}
