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

@Component({
  selector: 'app-customers-import-list',
  templateUrl: './customers-import-list.component.html',
  styleUrls: ['./customers-import-list.component.scss'],
  standalone : true,
  imports: [AdminPageHeaderComponent, TranslatePipes, FormsModule]
})
export class CustomersImportListComponent extends Unsub implements OnInit {
  form: FormGroup;
  Error = false;
  ErrorMessage: any;

  public sendingResponse: { [key: string]: boolean } = {};
  constructor(
    public fb: FormBuilder,
    private AdminService: AdminService,
    private toastr: ToastrService,
    private router: Router,
    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.form = this.fb.group({
      file: null,
    });
  }

  ngOnInit(): void {}

  file(event: any) {
    const file = (event.target as HTMLInputElement)?.files?.[0];
    this.form.patchValue({
      file: file,
    });
  }

  Importfile(res: any, buttonId) {
    const formData: any = new FormData();
    formData.append('file', this.form.controls['file'].value);

    const httpOptions = {
      headers: new HttpHeaders({
        Accept: 'application/json',
      }),
    };

    if (res?.value.file.includes('.csv') || res.value.file.includes('.xlsx')) {
      this.sendingResponse[buttonId] = true;
      this.AdminService.customercsv(formData, httpOptions)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            this.Error = false;
            if (res?.success) {
              this.form.reset({});
              Swal.fire({
                title: this.translate.transform('Imported Successfully'),
                text: this.translate.transform(res.success),
                icon: 'success',
                confirmButtonColor: '#6259ca',
              });
              this.router.navigate(['/admin/customer']);
            }
            if (res.error) {
              this.Error = true;
              if(typeof(res.error) == 'string'){
                this.ErrorMessage = res.error;
              }else{
                for (const el in res.error) {
                  this.ErrorMessage = res.errors[el];
                  this.toastr.error(this.translate.transform(res.errors[el]));
                }
              }
            }
          },
          error: () => {
             this.sendingResponse[buttonId] = false;
          },
        });
    } else {
      this.Error = true;
      this.ErrorMessage = this.translate.transform('The File Type Is Not Supported');
    }
  }
}
