import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, FormsModule } from '@angular/forms';
import { takeUntil } from 'rxjs';
import Swal from 'sweetalert2';
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';

@Component({
  selector: 'app-employee-upload-list',
  templateUrl: './employee-upload-list.component.html',
  styleUrls: ['./employee-upload-list.component.scss'],
  standalone : true,
  imports: [AdminPageHeaderComponent, TranslatePipes, FormsModule]
})
export class EmployeeUploadListComponent extends Unsub implements OnInit {
  form: FormGroup;
  Error = false;
  ErrorMessage: any;
  public sendingResponse: { [key: string]: boolean } = {};

  myform!: FormGroup;
  file!: FormControl;

  constructor(
    private adminService: AdminService,
    public fb: FormBuilder,
    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 {
    this.createFormControls();
    this.createForm();
  }

  createFormControls() {
    this.file = new FormControl('');
  }

  createForm() {
    this.myform = new FormGroup({
      file: this.file,
    });
  }

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

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

    this.sendingResponse[buttonId] = true;
    const httpOptions = {
      headers: new HttpHeaders({
        Accept: 'application/json',
      }),
    };
    if (ngForm.value.file.includes('.csv') || ngForm.value.file.includes('.xlsx')) {
      this.adminService
        .userimport(formData, httpOptions)
        .pipe(takeUntil(this.unSubscribe$))
        .subscribe({
          next: (res) => {
            this.sendingResponse[buttonId] = false;
            this.Error = false;
            if (res?.success) {
              Swal.fire({
                title: this.translate.transform('Imported Successfully'),
                text: this.translate.transform(res.success),
                icon: 'success',
                confirmButtonColor: '#6259ca',
              });
              this.form.reset({});
              this.router.navigate(['/admin/manage-roles/employees-list']);
            }
            if (res.error) {
              ngForm.reset();
              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');
    }
  }
}
