import { Component, OnInit } from '@angular/core';
import { takeUntil } from 'rxjs';
import { DomSanitizer, SafeHtml, Title } from '@angular/platform-browser';
import { Unsub } from '../../../shared/class/unsub.class';
import { GuestService } from '../../../shared/services/guest.service';
import { LoaderService } from '../../../shared/services/loader.service';

import { RouterLink } from '@angular/router';
import { NgbAccordionModule, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslatePipes } from '../../../shared/pipes/translate/translate.pipe';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from '@ngx-translate/core';
import { AdminService } from '../../../shared/services/admin/admin.service';
import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
@Component({
  selector: 'app-faqs',
  templateUrl: './faqs.component.html',
  styleUrls: ['./faqs.component.scss'],
  standalone : true,
  imports: [TranslatePipes, RouterLink, NgbAccordionModule, FormsModule, NgSelectModule]
})
export class FaqsComponent extends Unsub implements OnInit {
  faq: any;
  languages: any;
  public sendingResponse: { [key: string]: boolean } = {};
  faqloading = true;
  constructor(private guestService: GuestService,
      private modalService: NgbModal, private toastr: ToastrService,
          private translate: TranslatePipe, private adminService:AdminService,
    loaderService: LoaderService, private sanitizer: DomSanitizer) {
    /**
    * 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);
  }

  ngOnInit(): void {
    this.loaderService.showLoader();
    this.guestService
      .faq()
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.faq = res;
          this.languages = Object.keys(res.languages).map(key => ({ id: key, name: res.languages[key] }));
          this.loaderService.hideLoader();
          this.faqloading = false;
        },
        error: () => { this.loaderService.hideLoader(); this.faqloading = false; }
      });
  }
  sanitizeHtml(html: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }

  
  textToTranslate;
  selectedFaq;
  faqcatId;
  translateModel(content, faqcatId, faq) {
    // this.textToTranslate = this.ticketData?.ticket?.message;
    this.selectedFaq = faq
    this.faqcatId = faqcatId;
    this.modalService.open(content, { backdrop: 'static', keyboard: false, size: 'lg' });
  }

  translateFn(ngForm, buttonId) {
    if (ngForm.valid) {
      this.sendingResponse[buttonId] = true;
      let data = {
        text: this.selectedFaq.answer,
        title: this.selectedFaq.question,
        target_lang: ngForm.value.languages,
        user: 'customer',
      }
      this.adminService.translate(data).pipe(takeUntil(this.unSubscribe$)).subscribe({
        next:
          (res) => {
            this.sendingResponse[buttonId] = false;
            if (res.success) {
              this.toastr.success(this.translate.transform(res.success));
              this.modalService.dismissAll();
              this.faq.faqcats.map((faqcat)=>{
                if(faqcat.id  === this.faqcatId){
                  faqcat.faqdetails = faqcat.faqdetails.map((item) => {
                    if (item?.id === this.selectedFaq.id) {
                      return { ...item, answer: res.translated_text, question: res.translated_title }; // Update the specific FAQ's answer
                    }
                    return item;
                  });
                }
              })
            }
            if (res.message) {
              this.toastr.error(this.translate.transform('Translation failed: ' + res.message));
            }
            if (res?.error?.errors) {
              for (const el in res.error.errors) {
                this.toastr.error(this.translate.transform(res.error.errors[el]));
              }
            }
            else if (res.errors) {
              // Iterate through each error key (e.g., subcategoryname)
              Object.keys(res.errors).forEach(key => {
                // If there are errors for that key, display them
                res.errors[key].forEach((error: string) => {
                  this.toastr.error(this.translate.transform(error));
                });
              });
            }
          },
        error: () => {
          this.sendingResponse[buttonId] = false;
        },
      }
      );
    }
  }
}
