import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { lastValueFrom } from 'rxjs';
import { AlertComponent } from 'src/app/components/resources/dialogs/alert/alert.component';
import { ResponseDataSubcontratist, Subcontratist } from 'src/app/interfaces/personal-managment/subcontractist.interface';
import { ResponseData } from 'src/app/interfaces/response-data';
import { EncService } from 'src/app/services/enc/enc.service';
import { SubcontratistService } from 'src/app/services/personal-management/subcontratist.service';
import { ResourcesService } from 'src/app/services/resources/resources.service';

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

  public idSubcontratist: string;
  public enable: string;
  public btnSmall: boolean;
  public formGroup: FormGroup;
  public identificationLength: number;
  public isLoadingForm: boolean;

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _subcontratistService: SubcontratistService,
    private _router: Router,
  ) {
    this.idSubcontratist = "";
    this.enable = "";
    this.btnSmall = false;
    this.formGroup = this.createFormGroup();
    this.identificationLength = 13;
    this.isLoadingForm = false;

  }

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

private readOnlyForm(){
  this.enable == '1' ? this.socialReason?.enable() : this.socialReason?.disable();
  this.enable == '1' ? this.taxReference?.enable() : this.taxReference?.disable();
  this.enable == '1' ? this.RFC?.enable() : this.RFC?.disable();
  this.enable == '1' ? this.contractType?.enable() : this.contractType?.disable();
  this.enable == '1' ? this.email?.enable() : this.email?.disable();
  this.enable == '1' ? this.foreigner?.enable() : this.foreigner?.disable();
  this.enable == '1' ? this.tax?.enable() : this.tax?.disable();
  this.enable == '1' ? this.street?.enable() : this.street?.disable();
  this.enable == '1' ? this.exteriorNumber?.enable() : this.exteriorNumber?.disable();
  this.enable == '1' ? this.interiorNumber?.enable() : this.interiorNumber?.disable();
  this.enable == '1' ? this.suburb?.enable() : this.suburb?.disable();
  this.enable == '1' ? this.city?.enable() : this.city?.disable();
  this.enable == '1' ? this.postalCode?.enable() : this.postalCode?.disable();
  this.enable == '1' ? this.federalEntity?.enable() : this.federalEntity?.disable();
  this.enable == '1' ? this.country?.enable() : this.country?.disable();
  this.enable == '1' ? this.telephone1?.enable() : this.telephone1?.disable();
  this.enable == '1' ? this.lada1?.enable() : this.lada1?.disable();
  this.enable == '1' ? this.telephone2?.enable() : this.telephone2?.disable();
  this.enable == '1' ? this.lada2?.enable() : this.lada2?.disable();
}

  private createFormGroup() {
    return new FormGroup({
      socialReason: new FormControl('', Validators.required),
      taxReference: new FormControl(''),
      RFC: new FormControl('', [Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/))]),
      contractType: new FormControl('', Validators.required),
      email: new FormControl('', [Validators.required, Validators.email]),
      foreigner: new FormControl('', Validators.required),
      tax: new FormControl('', [Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/))]),
      street: new FormControl('', Validators.required),
      exteriorNumber: new FormControl('', Validators.required),
      interiorNumber: new FormControl(''),
      suburb: new FormControl('', Validators.required),
      city: new FormControl('', Validators.required),
      postalCode: new FormControl('', Validators.required),
      federalEntity: new FormControl('', Validators.required),
      country: new FormControl('', Validators.required),
      telephone1: new FormControl('', Validators.required),
      lada1: new FormControl('', Validators.required),
      telephone2: new FormControl(''),
      lada2: new FormControl(''),
    })
  }

  public async decript() {
    this.idSubcontratist = await this._encService.desencriptar(this.idSubcontratist);
    if (this.idSubcontratist != "0") {
      this.getData();
    }
    console.log(this.idSubcontratist);
  }

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

  public changeNationality() {
    if (this.enable == "1") {
      if (this.foreigner?.value == "Si") {
        this.RFC?.disable();
        this.RFC?.setValue(null);
        this.tax?.enable();
      } else {
        this.tax?.setValue(null);
        this.tax?.disable();
        this.RFC?.enable();
      }
    }
  }

  public onchangeType() {
    if (this.contractType.value == "Persona Moral") {
      this.identificationLength = 12;
      this.RFC.setValidators([Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/)), Validators.maxLength(12), Validators.minLength(12)])
      this.tax.setValidators([Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/)), Validators.maxLength(12), Validators.minLength(12)])
    } else {
      this.RFC.setValidators([Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/)), Validators.maxLength(13), Validators.minLength(13)])
      this.tax.setValidators([Validators.required, Validators.pattern(new RegExp(/^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/)), Validators.maxLength(13), Validators.minLength(13)])
      this.identificationLength = 13;
    }
    this.RFC.setValue(null);
    this.tax.setValue(null);
  }

  public alert() {
    if (this.idSubcontratist == "0") {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Registrar Subcontratista',
          description: '¿Está seguro que desea registrar al subcontratista?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.storeSubcontratist();
        }
      });
    } else {
      this._dialog.open(AlertComponent, {
        data: {
          title: 'Actualizar Subcontratista',
          description: '¿Está seguro que desea actualizar al subcontratista?',
          icon: 'warning',
        },
        disableClose: true,
      }).afterClosed().subscribe((result) => {
        if (result) {
          this.updateSubcontratist();
        }
      });
    }

  }

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

  private async updateSubcontratist() {
    this.isLoadingForm = true;
    await lastValueFrom(this._subcontratistService.updateSubcontratist(await this.subcontratistObject(), this.idSubcontratist)).then(
      (responseData: ResponseData) => {
        this._resourcesService.openSnackBar("¡Actualización Exitosa!");
        this._router.navigate(["/sam/GPRS/subcontratist"]);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
    this.isLoadingForm = false;
  }

  private async getData() {
    console.log(this.idSubcontratist);
    await lastValueFrom(this._subcontratistService.getSubcontratistById(this.idSubcontratist)).then(
      (responseData: ResponseDataSubcontratist) => {
        this.putDataOnForm(responseData.response);
      }, (error: HttpErrorResponse) => this._resourcesService.checkErrors(error)
    );
  }

  private async putDataOnForm(subcontratist: Subcontratist) {
    this.socialReason.setValue(subcontratist.SOCIAL_REASON)
    this.taxReference.setValue(subcontratist.TAX_REFERENCE)
    this.foreigner.setValue(subcontratist.FOREIGNER)
    this.contractType.setValue(subcontratist.CONTRACT_TYPE)
    this.RFC.setValue(subcontratist.RFC == null || subcontratist.RFC == "" ? null : await this._encService.desencriptar(subcontratist.RFC))
    this.tax.setValue(subcontratist.TAX == null || subcontratist.TAX == "" ? null : await this._encService.desencriptar(subcontratist.TAX))
    this.email.setValue(await this._encService.desencriptar(subcontratist.EMAIL))
    this.street.setValue(subcontratist.STREET)
    this.exteriorNumber.setValue(subcontratist.EXTERIOR_NUMBER)
    this.interiorNumber.setValue(subcontratist.INTERIOR_NUMBER)
    this.suburb.setValue(subcontratist.SUBURB)
    this.city.setValue(subcontratist.CITY)
    this.postalCode.setValue(subcontratist.POSTAL_CODE)
    this.federalEntity.setValue(subcontratist.FEDERAL_ENTITY)
    this.country.setValue(subcontratist.COUNTRY)
    this.telephone1.setValue(await this._encService.desencriptar(subcontratist.TELEPHONE1))
    this.lada1.setValue(subcontratist.LADA1)
    this.telephone2.setValue(subcontratist.TELEPHONE2 == null || subcontratist.TELEPHONE2 == "" ? null : await this._encService.desencriptar(subcontratist.TELEPHONE2))
    this.lada2.setValue(subcontratist.LADA2)
  }

  private async subcontratistObject(): Promise<Subcontratist> {
    return {
      SOCIAL_REASON: this.socialReason.value == null ? null : this.socialReason.value.trim(),
      TAX_REFERENCE: this.taxReference.value == null ? null : this.taxReference.value.trim(),
      RFC: this.RFC.value == null ? null : await this._encService.encriptar(this.RFC.value.trim()),
      CONTRACT_TYPE: this.contractType.value.trim(),
      EMAIL: await this._encService.encriptar(this.email.value.trim()),
      FOREIGNER: this.foreigner.value.trim(),
      TAX: this.tax.value == null ? null : await this._encService.encriptar(this.tax.value.trim()),
      STREET: this.street.value.trim(),
      EXTERIOR_NUMBER: this.exteriorNumber.value.toString().trim(),
      INTERIOR_NUMBER: this.interiorNumber.value == null || this.interiorNumber.value == null ? null : this.interiorNumber.value.toString().trim(),
      SUBURB: this.suburb.value,
      CITY: this.city.value,
      POSTAL_CODE: this.postalCode.value.toString().trim(),
      FEDERAL_ENTITY: this.federalEntity.value,
      COUNTRY: this.country.value,
      TELEPHONE1: await this._encService.encriptar(this.telephone1.value.toString().trim()),
      LADA1: this.lada1.value.trim(),
      TELEPHONE2: this.telephone2.value == null ? null : await this._encService.encriptar(this.telephone2.value.toString().trim()),
      LADA2: this.lada2.value == null ? null : this.lada2.value.trim(),
      SAVED_BY_USER: this._resourcesService.getUser(),
      LINE_NUMBER: 1
    }
  }

  get socialReason() {
    return this.formGroup.get('socialReason')!;
  }

  get taxReference() {
    return this.formGroup.get('taxReference')!;
  }

  get RFC() {
    return this.formGroup.get('RFC')!;
  }

  get contractType() {
    return this.formGroup.get('contractType')!;
  }

  get email() {
    return this.formGroup.get('email')!;
  }

  get foreigner() {
    return this.formGroup.get('foreigner')!;
  }

  get tax() {
    return this.formGroup.get('tax')!;
  }

  get street() {
    return this.formGroup.get('street')!;
  }

  get exteriorNumber() {
    return this.formGroup.get('exteriorNumber')!;
  }

  get interiorNumber() {
    return this.formGroup.get('interiorNumber')!;
  }

  get suburb() {
    return this.formGroup.get('suburb')!;
  }

  get city() {
    return this.formGroup.get('city')!;
  }

  get postalCode() {
    return this.formGroup.get('postalCode')!;
  }

  get federalEntity() {
    return this.formGroup.get('federalEntity')!;
  }

  get country() {
    return this.formGroup.get('country')!;
  }

  get telephone1() {
    return this.formGroup.get('telephone1')!;
  }

  get lada1() {
    return this.formGroup.get('lada1')!;
  }

  get telephone2() {
    return this.formGroup.get('telephone2')!;
  }

  get lada2() {
    return this.formGroup.get('lada2')!;
  }

}
