import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { Contract, Hour, ResponseDataContract } from 'src/app/interfaces/personal-managment/intervention.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { EncService } from 'src/app/services/enc/enc.service';
import { EmployeeService } from 'src/app/services/personal-management/employee.service';
import { InterventionService } from 'src/app/services/personal-management/intervention.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

@Component({
  selector: 'app-contract-form',
  templateUrl: './contract-form.component.html',
  styleUrls: ['./contract-form.component.css']
})
export class ContractFormComponent implements OnInit {

  public idContract: string;
  public enable: string;
  public btnSmall: boolean;
  public formGroup: FormGroup;
  public formData: FormData = new FormData();
  public isLoadingForm: boolean;
  public interns!: Array<any>;
  public subcontratists!: Array<any>;
  public document!: Array<any>;

  public dataSource?: MatTableDataSource<any>;
  public displayedColumns: string[] = ['name', 'size', 'action'];
  public hours: Hour[];

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _interventionService: InterventionService,
    private _employeeService: EmployeeService,
    private _encService: EncService,
    private _router: Router,
    private _dialog: MatDialog,
  ) {
    this.idContract = "";
    this.enable = "";
    this.btnSmall = false;
    this.formGroup = this.createFormGroup();
    this.isLoadingForm = false;
    this.document = [];
    this.hours = [];
    this.subcontratists = [];
    this.interns = [];
  }

  ngOnInit(): void {
    this.enable = this._activatedRoute.snapshot.paramMap.get('enable')!;
    this.idContract = this._activatedRoute.snapshot.paramMap.get('id')!;
    this.getEmployees();
    this.setHours();
    this.decript();
  }

  private async getEmployees() {
    await lastValueFrom(this._employeeService.getConsultOfEmployees()).then(
      (responseData: any) => {
        responseData.response.forEach((element: any) => {
          if (element.STATUS === "Activo") {
            if (element.CONTRACT_TYPE == "Interno") {
              this.interns.push(element);
            } else {
              this.subcontratists.push(element);
            }
          }
        });
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }


  private createFormGroup() {
    return new FormGroup({
      contractType: new FormControl('', Validators.required),
      denominationIntern: new FormControl('', Validators.required),
      denominationSubcontratist: new FormControl('', Validators.required),
      startDate: new FormControl('', Validators.required),
      endDate: new FormControl('', Validators.required),
      startHour: new FormControl('', Validators.required),
      endHour: new FormControl('', Validators.required),
      cost: new FormControl('', Validators.required),
      documentsInput: new FormControl('', Validators.required),
    })
  }

  private async decript() {
    this.idContract = await this._encService.desencriptar(this.idContract);
    if (this.idContract != "0") {
      this.getData();
    }
  }

  public changeContractType() {
    if (this.enable == "1") {
      if (this.contractType?.value == "Subcontratista") {
        this.denominationSubcontratist?.enable();
        this.denominationIntern?.disable();
        this.denominationIntern?.setValue(null);
      } else {
        this.denominationIntern?.enable();
        this.denominationSubcontratist?.disable();
        this.denominationSubcontratist?.setValue(null);
      }
    }
  }

  public alert() {
    this._dialog.open(AlertComponent, {
      data: {
        title: 'Registrar Contrato',
        description: '¿Está seguro que desea registrar el contrato?',
        icon: 'warning',
      },
      disableClose: true,
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.storeContract();
      }
    });

  }

  public datesRange() {
    if (this.startDate.touched && this.endDate.touched) {
      this.hoursRange();
      if (this.startDate.value > this.endDate.value) {
        this._resourcesService.openSnackBar("La fecha de fin es menor a la de inicio");
        this.endDate.setValue(null);
      }
    }
  }

  public hoursRange() {
    if (this.startHour.touched && this.endHour.touched && this.startDate.touched && this.endDate.touched) {
      if (this.startDate.value.toString() == this.endDate.value.toString()) {
        if (this.startHour.value > this.endHour.value) {
          this._resourcesService.openSnackBar("La hora de fin es menor a la de inicio");
          this.endHour.setValue(null);
        }
      }
    }
  }

  private async storeContract() {
    this.isLoadingForm = true;
    await lastValueFrom(this._interventionService.storeContract(await this.contractObject())).then(
      (responseData: ResponseData) => {
        this._resourcesService.openSnackBar("¡Registro Exitoso!");
        this._router.navigate(["/sam/GPRS/intervention"]);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private async getData() {
    await lastValueFrom(this._interventionService.getContractById(this.idContract)).then(
      (responseData: ResponseDataContract) => {
        if (this.enable != "1") {

          this.subcontratists.forEach(element => {
            if (element.ID_EMPLOYEE == responseData.response.DENOMINATION) {
              responseData.response.DENOMINATION = element.NAME;
            }
          });

          this.interns.forEach(element => {
            if (element.ID_EMPLOYEE == responseData.response.DENOMINATION) {
              responseData.response.DENOMINATION = element.NAME;
            }
          });

        }
        this.putDataOnForm(responseData.response);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private async putDataOnForm(contract: Contract) {
    this.contractType.setValue(contract.CONTRACT_TYPE)
    this.cost.setValue(await this._encService.desencriptar(contract.CONTRACT_COST))
    if (this.contractType.value === "Subcontratista") {
      this.denominationSubcontratist.setValue(contract.DENOMINATION)
    } else {
      this.denominationIntern.setValue(contract.DENOMINATION)
    }

    let startDate = contract.START_DATE.split(' ');
    let startHour = startDate[1];
    startDate = new Date(`${startDate[0].split('-')[2]}-${startDate[0].split('-')[1]}-${startDate[0].split('-')[0]}T00:00:00.000`);
    this.startDate.setValue(startDate);

    let endDate = contract.END_DATE.split(' ');
    let endHour = endDate[1];
    endDate = new Date(`${endDate[0].split('-')[2]}-${endDate[0].split('-')[1]}-${endDate[0].split('-')[0]}T00:00:00.000`);
    this.endDate.setValue(endDate);

    this.hours.forEach(hour => {
      if (hour.value == startHour) {
        this.startHour.setValue(hour.label);
      }

      if (hour.value == endHour) {
        this.endHour.setValue(hour.label);
      }
    });

  }

  private async contractObject(): Promise<FormData> {
    this.formData.append('CONTRACT_TYPE', this.contractType.value);
    this.formData.append('DENOMINATION', this.denominationIntern.value != null ? this.denominationIntern.value : this.denominationSubcontratist.value);
    this.formData.append('START_DATE', this.buildDate(this.startDate.value) + " " + this.startHour.value);
    this.formData.append('END_DATE', this.buildDate(this.endDate.value) + " " + this.endHour.value);
    this.formData.append('CONTRACT_COST', await this._encService.encriptar(this.cost.value.toString()));
    if (this.document.length > 0) { this.formData.append('DOCUMENT', this.document[0]); }
    this.formData.append('SAVED_BY_USER', this._resourcesService.getUser());
    this.formData.append('LINE_NUMBER', "1");
    return this.formData;
  }


  checkFile(event: any) {

    if ((event.target.files[0].name.split(".")[1] != 'pdf') && (event.target.files[0].name.split(".")[1] != 'jpg')
      && (event.target.files[0].name.split(".")[1] != 'png') && (event.target.files[0].name.split(".")[1] != 'docx')) {
      this.documentsInput.reset();
      this.document = [];
      return this._resourcesService.openSnackBar('Solo se permiten archivos PDF, JPG, PNG, o DOCX');
    }
    this.document.push(event.target.files[0]);
    this.dataSource = new MatTableDataSource(this.document);

  }

  private setHours() {
    for (let i = 0; i <= 23; i++) {
      let timeLapse = i < 12 ? 'AM' : 'PM';
      let hour = i > 12 ? i - 12 : i;
      let hourStr = hour < 10 ? `0${hour}` : `${hour}`;

      let ent = `${hourStr}:00 ${timeLapse}`;
      let half = `${hourStr}:30 ${timeLapse}`;
      let hs = i < 10 ? `0${i}` : `${i}`;

      let entHour: Hour = {
        value: `${hs}:00:00`,
        label: ent
      }

      let halfHour: Hour = {
        value: `${hs}:30:00`,
        label: half
      }

      this.hours.push(entHour);
      this.hours.push(halfHour);
    }
  }

  private buildDate(date: any) {
    let dateObj = new Date(date!);
    let month = (dateObj.getMonth() + 1) < 10 ? `0${(dateObj.getMonth() + 1)}` : (dateObj.getMonth() + 1);
    let day = dateObj.getDate() < 10 ? `0${dateObj.getDate()}` : dateObj.getDate();
    return `${dateObj.getFullYear()}-${month}-${day}`;
  }

  public deleteFiles() {
    this.documentsInput.reset();
    this.document = [];
    this.dataSource = new MatTableDataSource(this.document);
  }

  // Método para reajustar los botones según sus dimensiones
  public onResize(): void {
    this.btnSmall = window.innerWidth <= 1405;
  }

  get contractType() {
    return this.formGroup.get('contractType')!;
  }
  get denominationIntern() {
    return this.formGroup.get('denominationIntern')!;
  }
  get denominationSubcontratist() {
    return this.formGroup.get('denominationSubcontratist')!;
  }
  get startDate() {
    return this.formGroup.get('startDate')!;
  }
  get endDate() {
    return this.formGroup.get('endDate')!;
  }
  get startHour() {
    return this.formGroup.get('startHour')!;
  }
  get endHour() {
    return this.formGroup.get('endHour')!;
  }
  get cost() {
    return this.formGroup.get('cost')!;
  }
  get documentsInput() {
    return this.formGroup.get('documentsInput')!;
  }

}
