import { DOCUMENT } from "@angular/common";
import { Component, Inject, OnDestroy, OnInit } from "@angular/core";
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
} from "@angular/forms";
import { MatDialog } from "@angular/material/dialog";
import { tap } from "rxjs/operators";
import { ReportingService } from "src/app/services/reporting.service";
import { ToastService } from "src/app/services/toast.service";
import { DataService } from "src/app/core/services/data.service";

@Component({
  selector: "app-modal-generate-reporting",
  templateUrl: "./modal-generate-reporting.component.html",
  styleUrls: ["./modal-generate-reporting.component.scss"],
})
export class ModalGenerateReportingComponent implements OnInit, OnDestroy {
  public templatesList = [
    {
      id: "",
      name: "",
    },
  ];
  public isLoading = false;
  public data!: [];
  public labelSearch = "Nom de compte";
  public keyword = "name";
  public errorMsg = "";
  public dataFindBy = [
    {
      id: 1,
      name: "Nom de compte ",
      value: "accountName",
    },
    {
      id: 1,
      name: "Nom de groupe",
      value: "accountGroup ",
    },
  ];

  public isLoadingResult = false;
  public form: FormGroup;
  public submitted = false;
  constructor(
    public dialog: MatDialog,
    private reporting: ReportingService,
    private toast: ToastService,
    private formBuilder: FormBuilder,
    public dataService: DataService,

    @Inject(DOCUMENT) private document: Document
  ) {
    this.document.body.classList.add("pop-report");
    this.form = this.formBuilder.group({
      // find_by: ["accountName", [Validators.required]],
      // account_name: ["", [Validators.required]],
      // template: ["", [Validators.required]],
    });

    // this.form.get("find_by")?.valueChanges.subscribe((data) => {
    //   this.data = [];
    //   this.isLoadingResult = false;
    //   this.form.patchValue({
    //     account_name: "",
    //   });

    //   data === "accountName"
    //     ? (this.labelSearch = "Nom de compte")
    //     : (this.labelSearch = "Nom de groupe");
    // });
  }

  ngOnInit(): void {
    // this.reporting
    //   .listTemplate()
    //   .pipe(
    //     tap((res: any) => {
    //       console.log("res", res.templates);
    //       res.success
    //         ? (this.templatesList = res.templates)
    //         : this.toast.showError(
    //             "Une erreur est survenue pour lister vos templates"
    //           );
    //     })
    //   )
    //   .subscribe();
  }

  public closeDialog() {
    this.dialog.closeAll();
  }

  public getServerResponse(event: string) {
    this.isLoadingResult = true;
    if (event) {
      this.reporting
        .getAutocompletion(this.form.value.find_by, event)
        .subscribe(
          (data) => {
            data.length > 0 ? (this.data = data) : (this.data = []);
            this.isLoadingResult = false;
          },
          (err) => {
            (this.errorMsg = "erreur depuis nos serveur , desole"),
              (this.isLoadingResult = false);
          }
        );
    } else {
      this.isLoadingResult = false;
    }
  }

  public getServerResponseGroup(event: string) {
    this.isLoadingResult = true;
    if (event) {
      this.reporting
        .getAutocompletionGroup(this.form.value.find_by, event)
        .subscribe(
          (data) => {
            data.length > 0 ? (this.data = data) : (this.data = []);
            this.isLoadingResult = false;
          },
          (err) => {
            (this.errorMsg = "erreur depuis nos serveur , desole"),
              (this.isLoadingResult = false);
          }
        );
    } else {
      this.isLoadingResult = false;
    }
  }

  public selectEvent(item: any) {
    // this.form.value.account_name = item.id;
    // do something with selected item
  }

  public selectEventGroup(item: any) {
    //  this.form.value.account_name = item.name;
    // do something with selected item
  }

  public onChangeSearch(val: string) {
    // fetch remote data from here
    // And reassign the 'data' which is binded to 'data' property.
  }

  public onFocused(e: any) {
    // do something when input is focused
  }

  public searchCleared() {
    this.data = [];
  }

  public generateReporting() {
    this.submitted = true;
    if (this.form.invalid || this.isLoading) {
      this.toast.showError("Merci de verifier le champ requis");
      return;
    }

    this.isLoading = true;
    let payload = {};

    payload = {
      accountName: this.form.value.account_name.id,
      templateId: this.form.value.template,
    };

    this.reporting
      .genetateReporting(payload, this.form.value.account_name.name)
      .subscribe((data: boolean) => {
        this.isLoading = false;
        if (data) {
          this.dialog.closeAll();
        }
      });
  }

  public generateReportingGroup() {
    this.submitted = true;
    if (this.form.invalid || this.isLoading) {
      this.toast.showError("Merci de verifier le champ requis");
      return;
    }

    this.isLoading = true;
    let payload = {};

    payload = {
      accountGroup: this.form.value.account_name.name,
      templateId: this.form.value.template,
    };

    this.reporting
      .genetateReportingGroup(payload)
      .subscribe((data: boolean) => {
        this.isLoading = false;
        if (data) {
          this.dialog.closeAll();
        }
      });
  }

 // Ajoutez une variable pour stocker le fichier sélectionné
selectedFile: File | null = null;

public onFileSelected(event: any) {
  const file = event.target.files[0];
  if (file) {
    const fileExtension = file.name.split(".").pop().toLowerCase();
    const allowedExtensions = ["csv", "xls", "xlsx"];
    if (!allowedExtensions.includes(fileExtension)) {
      this.form?.controls["file"]?.setErrors({ invalidFormat: true });
    } else {
      this.form?.controls["file"]?.setErrors(null);
      this.selectedFile = file;
    }
  } else {
    this.form.controls["file"].setErrors({ required: true });
  }
}

public async importingData() {
  this.submitted = true;
  this.isLoading = true;
  try {
      // Récupération du fichier
      const fileInput = (document.querySelector('input[type="file"]') as HTMLInputElement)?.files?.[0];
      if (!fileInput) {
          this.toast.showError("Le fichier est requis");
          this.isLoading = false;
          return;
      }
    const formData = new FormData();
    formData.append("file", fileInput);
      const response = await this.dataService.import(formData).toPromise();
      if (response.success) {
          this.toast.showSuccess("Importation réussie");
          const modulesTraites = response.modules_traités
          setTimeout(() => {
            window.location.reload();
        }, 2000);
      } else {
        console.log('message erreur:',response);
          this.toast.showError(response.error);
      }
  } catch (error) {
      this.toast.showError("Erreur dans le fichier importé: " + (error as any)?.error?.error || 'Erreur inconnue');
  } finally {
      this.isLoading = false;
  }
}


 

  get f(): { [key: string]: AbstractControl } {
    return this.form.controls;
  }

  ngOnDestroy(): void {
    this.document.body.classList.remove("pop-report");
  }
}
