import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { takeUntil } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
import { TranslatePipe } from '@ngx-translate/core';
import { Unsub } from '../../../../shared/class/unsub.class';
import { LanguagesService } from '../../../../shared/services/admin/languages.service';
import { LoaderService } from '../../../../shared/services/loader.service';
import { CommonModule } from '@angular/common';
import { MaterialeModules } from '../../../../material.module';
import { NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslatePipes } from '../../../../shared/pipes/translate/translate.pipe';
import { AdminPageHeaderComponent } from '../../../../shared/common/pageheader/admin-page-header/admin-page-header.component';
import { FormsModule } from '@angular/forms';
import Swal from 'sweetalert2';
import { AdminService } from '../../../../shared/services/admin/admin.service';
@Component({
  selector: 'app-translate-language',
  templateUrl: './translate-language.component.html',
  styleUrls: ['./translate-language.component.scss'],
  standalone : true,
  imports : [CommonModule, AdminPageHeaderComponent, TranslatePipes, MaterialeModules, NgbTooltipModule, NgbDropdownModule, FormsModule ]
})
export class TranslateLanguageComponent extends Unsub implements OnInit {
  public language: any;
  languagesKey: any;
  transCount: any;
  groups: any;
  active: any;
  isloader = true;
  public sendingResponse: { [key: string]: boolean } = {};
  public userId!: string;
  constructor(
    private languagesService: LanguagesService,
    private route: ActivatedRoute,
    private toastr: ToastrService,
    private adminService: AdminService,
    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);
    route.params.pipe(takeUntil(this.unSubscribe$)).subscribe({
      next: (params) => {
        this.userId = params['id'];
        this.translateFn();
      },
    });
  }

  ngOnInit(): void { }

  translateFn() {
    this.loaderService.showLoader();
    this.isloader = true;
    this.languagesService
      .languagesValues(this.userId)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.languagesKey = res.translates;
          this.language = res.language;
          this.transCount = res.translates_count;
          this.groups = res.groups;
          this.active = res.active;
          this.isloader = false;
          this.loaderService.hideLoader();
        },
       error: () => {this.isloader = true;  this.loaderService.hideLoader()}
      }); 
  }
  autoTranslateFn(){

    Swal.fire({
      icon: 'warning',
      title: this.translate.transform('Are you sure you want to continue?'),
      text: this.translate.transform('This might take a while to be done. Please be patient for the next few minutes.'),
      showCancelButton: true,
      confirmButtonColor: '#6259ca',
      cancelButtonColor: '#f11541',
      cancelButtonText: this.translate.transform('Close'),
      reverseButtons: true,
    }).then((result: any) => {
      if (result.isConfirmed) {
        this.startTranslationProcess();
      }
    });
  }
  
  working: boolean = false;
  startTranslationProcess(): void {
    // Show loading and blur the page
    document.querySelector('#loadingDiv')?.classList.remove('d-none');
    const colElement = document.querySelector('.col-xl-12') as HTMLElement;
    colElement.style.filter = 'blur(1px)';
    colElement.style.pointerEvents = 'none';

    const languageCode = { lang : this.userId};  // Replace with the actual language code

    this.working = true;

    // Call translation service
    this.adminService.autoTranslate(languageCode).subscribe({
      next: (responseData) => {
        if (responseData.success) {
          localStorage.setItem('success', responseData.success);
          this.toastr.success(this.translate.transform(responseData.success));
        } else {
          localStorage.setItem('error', responseData.error);
          this.toastr.error(this.translate.transform(responseData.error));
        }
      },
      error: (error) => {
        if (error.name === 'AbortError') {
          console.log('Translation process was cancelled.');
        } else {
          console.error('An error occurred:', error);
        }
        location.reload();
      },
      complete: () => {
        // Hide loading and reset blur
        document.querySelector('#loadingDiv')?.classList.add('d-none');
        colElement.style.filter = 'none';
        colElement.style.pointerEvents = '';
        this.working = false;
      }
    });
  }
  ChangeTheValues(data: any, buttonId) {
    this.isloader = true;
    if (this.language.languagecode == this.userId) {
      const UpdateData = {
        values: data,
      };
      this.sendingResponse[buttonId] = true;
      this.languagesService
        .translateUpdate(this.language.id, UpdateData)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            this.isloader = false;
            if (res?.success) {
              this.toastr.success(this.translate.transform(res.success));
            }
          },
          error: () => {
            this.isloader = false;
           this.sendingResponse[buttonId] = false;
          },
        });
    }
  }
  filterTranslate(data: any, buttonId) {
    this.isloader = true;
    this.sendingResponse[buttonId] = true;
    this.languagesService
      .translateFilter(this.userId, data.value.search)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          this.languagesKey = res.translates;
          this.language = res.language;
          this.transCount = res.translates_count;
          this.groups = res.groups;
          this.active = res.active;
          this.isloader = false;
        },
        error: () => {
          this.isloader = false;
         this.sendingResponse[buttonId] = false;
        },
      });
  }
  translateFilterNotTran(key, value, buttonId) {
    this.isloader = true;
    this.sendingResponse[buttonId] = true;
    this.languagesService
      .translateFilterNotTran(this.userId, key, value)
      .pipe(takeUntil(this.unSubscribe$))
      .subscribe({
        next: (res) => {
          this.sendingResponse[buttonId] = false;
          this.languagesKey = res.translates;
          this.language = res.language;
          this.transCount = res.translates_count;
          this.groups = res.groups;
          this.active = res.active;
          this.isloader = false;
        },
        error: () => {
          this.isloader = false;
         this.sendingResponse[buttonId] = false;
        },
      });
  }
  translateTab(groupname, buttonId) {
    if (groupname !== 'missing-translations') {
      this.isloader = true;
      this.sendingResponse[buttonId] = true;
      this.languagesService
        .translateGroup(this.userId, groupname)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            this.languagesKey = res.translates;
            this.language = res.language;
            this.transCount = res.translates_count;
            this.groups = res.groups;
            this.active = res.active;
            this.isloader = false;
          },
          error: () => {
            this.isloader = false;
           this.sendingResponse[buttonId] = false;
          },
        });
    }
  }

  allTrans() {
    this.translateFn();
  }
}
