import { Component, OnInit } from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
import { FormArray, FormBuilder, FormGroup, UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { ResizeEvent } from 'angular-resizable-element';
import { SignatureForm } from 'src/app/modules/signataireForm';
import { Demande } from 'src/app/modules/demande';
import { ApiService } from 'src/app/services/api.service';
import { TypeDocument } from 'src/app/modules/typeDocument';
import { UserPosition } from 'src/app/modules/userPosition';
import { Router } from '@angular/router';
import { PdfService } from 'src/app/services/pdf.service';
import { DemandeService } from 'src/app/services/demande.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Destinataire } from 'src/app/modules/destinataire';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-historique',
  templateUrl: './historique.component.html',
  styleUrls: ['./historique.component.scss']
})
export class HistoriqueComponent implements OnInit{
  demande : Demande = new Demande();
  validateForm!: FormGroup;
  validateFormMoal!: FormGroup;
  list_signataire: number[] = [1];
  signataire! : string ;
  hidesignataire : boolean = false;
  files_list : any [] = [];
  file! : File;
  step = 0;
  zoomFactor: number = 1.2;
  height = 432;
  width = 304;
  indexImage = 0;
  imageSrc = "";

  tdocuments: TypeDocument[] = [];

  signataireForm : SignatureForm = new SignatureForm();
  destinataires : any [] = [];
  signataireLIst : UserPosition[]  = [];
  isVisible = false;
  images : string[] = [];
  paginationTotal: any;
  isVisibleRecap = false;
  existed = false;

  constructor(private fb: FormBuilder, private apiService: ApiService, private router : Router, private spinnerTemplate: NgxSpinnerService,
    private pdfToImageService: PdfService, private demandeService: DemandeService, private message: NzMessageService
  ){

  }
  
  get users(): FormArray {
    return this.validateForm.get('users') as FormArray;
  }

  get files(): FormArray {
    return this.validateForm.get('files') as FormArray;
  }


  deleteFile(){
    this.files_list = [];
  }

  nextImage(): void {
    if(this.indexImage < this.images.length-1){
      this.indexImage = this.indexImage + 1;
    }
  }
  previousImage(): void {
    if(this.indexImage >  0){
      this.indexImage = this.indexImage - 1;
    }
  }

  deleteUser(index : number){
    this.users.controls.splice(index, 1);
  }

  onResizeEnd(event: ResizeEvent): void {
    console.log('Element was resized', event);
  }
  
  ngOnInit(): void {


    this.demande =  JSON.parse(localStorage.getItem('request_')!);
    this.demande.destinataires = this.demande.destinataires.sort((a, b) => a.place - b.place);
    this.destinataires = this.demande.destinataires;
    this.validateForm = this.fb.group({
      users: this.fb.array([]),
    });
    this.validateFormMoal = this.fb.group({
      file: [null, [Validators.required]],
      objet: ['', Validators.required],
      message: ['', Validators.required],
    })
    console.log(this.demande);
    this.getFile(this.demande.documents[0].directory);
  }

  createItem(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      envoie: ["En séquence", [Validators.required]],
      role : ["Observateur", [Validators.required]],
      statut : ["Initial", [Validators.required]],
      // Ajoutez d'autres champs ici si nécessaire
    });
  }

  createItemFile(): FormGroup {
    return this.fb.group({
      file: ["",Validators.required],
    });
  }

  showModal(image:string): void {
    this.imageSrc = image
    this.isVisible = true;
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  filename! : string;  

  getFile(filename: string){
    this.filename = filename;
    this.apiService.getFile(filename).subscribe(image => {
        console.log(image);
        this.convertPdfToImages(image);
    })
  }

  donwloadFile(){
    this.apiService.getFile(this.filename).subscribe(image => {
      const blob = new Blob([image], { type: 'application/pdf' });
      const url = window.URL.createObjectURL(blob);
      window.open(url, '_blank');
    })
  }

  async convertPdfToImages(file : File) {
    if (!file) {
      console.error('Aucun fichier PDF sélectionné.');
      return;
    }
    try {
      console.log("images")

      this.images = await this.pdfToImageService.convertToImage(file);
      this.paginationTotal = this.images.length
    } catch (error) {
      console.error('Une erreur est survenue lors de la conversion du PDF en images:', error);
    }
  }

  getTDocuments(){
      this.apiService.getDocuments().subscribe((data: any) => {
          console.log(data);
          this.tdocuments = data.response_data;
          this.validateForm = this.fb.group({
            users: this.fb.array([]),
          });

      })
  }

  relaunchUser(destinataire : Destinataire){
    this.spinnerTemplate.show();
      this.demandeService.relaunchDemand(this.demande.id, destinataire.id).subscribe((data:any) => {
         if(data.status_code == "000"){
          this.spinnerTemplate.hide();
          this.createMessage("info", "Le destinataire "+ destinataire.name +" a été relancé.");
         }else{
          this.spinnerTemplate.hide();
          this.createMessage("error", "Le destinataire "+ destinataire.name +" n'a pas été relancé.");
         }
      }, error => {
        this.spinnerTemplate.hide();
        this.createMessage("error", "Le destinataire "+ destinataire.name +" n'a pas été relancé.");
      })
  }

  cancelDemand(idDemand : number, enableRoot : boolean){
    this.spinnerTemplate.show();
      this.demandeService.cancelDemand(idDemand).subscribe((data:any) => {
         if(data.status_code == "000"){
          this.spinnerTemplate.hide();
          this.createMessage("info", "Votre demande a été annulée.");
          if(enableRoot == true){
            setTimeout(() => {
              this.isVisible = false;
                this.router.navigate(["home/signature"])
            }, 2000);
          }
         }else{
          this.spinnerTemplate.hide();
          this.createMessage("error", "Votre demande n'a pas été annulée.");
         }
      }, error => {
        this.spinnerTemplate.hide();
        this.createMessage("error", "Votre demande n'a pas été annulée.");
      })
  }


  createMessage(type: string, messqge: string): void {
    this.message.create(type, messqge);
  }


  removeItem(index: number): void {
    this.users.removeAt(index);
  }

  addItem(){
    console.log(this.users)
    this.existed = false;
    if(this.users.status == "VALID"){
      let data = this.users.controls;
      this.users.controls.forEach((element:any) => {
          data.forEach((dt:any, index:number) => {
            if(index > 0){
              if(dt.email == element.email){
                  this.existed = true;
              }
            }
          })
      })
      this.demande.destinataires.forEach((element:any) => {
        data.forEach((dt:any, index:number) => {
          if(index > 0){
            if(dt.email == element.email){
                this.existed = true;
            }
          }
        })
      })
      if(this.existed == false){
        this.users.push(this.createItem());
      }else{
        this.createMessage("warning", "Ce destinataire existe déjà. Veuillez le changer.")
      }

    }else{
      this.createMessage("error", "Veuillez remplir tous les champs du destinataire.")
    }
  }

  addFiles(){
    this.files.push(this.createItemFile());
  }

  fileObserver($event : any){
    console.log($event);
    this.files_list.push($event.target.files[0]);
    console.log(this.files_list)
  } 

  setSignature(event : any){
    console.log(this.validateForm)
    if(this.validateForm.value.signataire == "seul"){
      this.hidesignataire = true;
    }else{
      this.hidesignataire = false
    }
  }

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.users.controls, event.previousIndex, event.currentIndex);
    moveItemInArray(this.users.value, event.previousIndex, event.currentIndex);
  }

  showModalRelaunch(){
    if(this.validateForm.valid){
      this.isVisibleRecap = true;
    }else{
      this.createMessage("error", "Veuillez remplir tous les champs du destinataire.")
    }
  }



  submitForm(): void {
    this.isVisibleRecap = false;
    console.log(this.validateFormMoal);
    var newDemand = new Demande()
    if(this.validateFormMoal.valid){

      if(this.existed == false){
        var stateP = false;
        var stateE = false;
        console.log("1");
        var  destinatairesArray : any [] = []
        this.destinataires.forEach((element : any) => {
          destinatairesArray.push(element);
        })
        this.validateForm.value.users.forEach((element:any, i:number ) => {
          destinatairesArray.push(element);
        });
        console.log("2");
        destinatairesArray.map((element:any, i:number ) => {
          if(element.id){
                element.id = null;
                element.statut = "Initial";
                element.creationDate = null;
                element.modificationDate = null;
                element.positions =  [];          
          } 
            if(i > 0){
              let previousUser = destinatairesArray[i-1];
              if(previousUser.envoie == "En séquence"){
                if(element.envoie == "En séquence"){
                  element.place = previousUser.place + 1;
                }else{
                  element.place = previousUser.place + 1;
                };
              }else{
                  element.place = previousUser.place ;
              }
              if(element.envoie == "En séquence")
                stateP = true;
              else if(element.envoie == "En parallèle")
                stateE = true;
            }
        });
       // console.log(destinatairesArray);
        if(destinatairesArray.length > 1){
          if(!stateE && stateP){
            newDemand.edemande = "En séquence";
          }else if(stateE && !stateP){
            newDemand.edemande = "En parallèle";
          }else if(stateE && stateP){
            newDemand.edemande = "En simultanée";
          }
        }else{
          console.log("4");
          let previousUser = destinatairesArray[0];
          console.log(previousUser)
          newDemand.edemande = previousUser.envoie;
        }
  
        this.signataireForm.setObjet(this.demande.typeDocument.name, destinatairesArray, this.files_list[0], this.validateFormMoal.value.objet,
          this.validateFormMoal.value.message)
          newDemand.typeDocument = this.demande.typeDocument;
          newDemand.confidentiality = this.demande.confidentiality;
          newDemand.priority = this.demande.priority;
          newDemand.expirationDate = this.demande.expirationDate;
          newDemand.documents = [];
          newDemand.objetMail = this.validateFormMoal.value.objet
          newDemand.message = this.validateFormMoal.value.message
          newDemand.destinataires = destinatairesArray;
          newDemand.user = JSON.parse(localStorage.getItem("user")!);
          this.signataireForm.demande = newDemand;
          console.log(this.signataireForm);
  
          this.cancelDemand(this.demande.id, false);
          this.step = 1;
      }else{
        this.createMessage("warning", "Vous avez dupliqué des informations  d'un destinataire. Veuillez le changer.")
      }
    }else{
      this.createMessage("error", "Votre formulaire de demande est incomplet. Veuillez remplir tous les champs.")
    }
    // Vous pouvez envoyer les données à votre backend ici
  }

  maMethodeDansLeParent() {
    this.step = 0;
  }




}
