import {
  Component,
  OnInit,
  OnDestroy,
  ViewChild,
  ChangeDetectorRef,
  AfterViewInit,
} from '@angular/core';
import { WorkflowFormComponent } from '../../samwf/workflow-form/workflow-form.component';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { lastValueFrom, Observable } from 'rxjs';
import { ProgressBarMode } from '@angular/material/progress-bar';
import { RequestWorkflowFormComponent } from './request-workflow-form/request-workflow-form.component';
import { ResponseData } from 'src/app/interfaces/response-data';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-workflow-request-workflow',
  templateUrl: './workflow-request-workflow.component.html',
  styleUrls: ['./workflow-request-workflow.component.css'],
})
export class WorkflowRequestWorkflowComponent implements AfterViewInit {
  workflows: any[] = [];
  data_empty = false;
  data: any;
  statusData: any[] = [
    { state: 0, textState: 'Pendientes' },
    { state: 1, textState: 'Validadas' },
  ];
  requests: any[] = [];
  selectedOpcion = 0;
  filter_empty = false;
  displayedColumns: string[] = [
    'name',
    'modulo',
    'created_at',
    'updated_at',
    'accion',
  ];

  public dataSource: MatTableDataSource<any>;

  public isLoading: boolean = true;
  public isLoadingForm: boolean = false;

  // ---- SmartPage ----
  public btnSmall: boolean = false;
  public card_size = 'card-size-normal mat-elevation-z8';

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;

  minDate: Date;
  maxDate: Date;
  modules: any[] = [];

  filterCreatedDate: any = '';
  filterValidatedDate: any = '';
  filterModule: any = '';
  isLoadingComponent = false;

  constructor(
    public dialog: MatDialog,
    private router: Router,
    private translate: TranslateService,
    private _samwfService: WorkflowService,
    private changeDetectorRef: ChangeDetectorRef,
    private _snackBar: MatSnackBar,
    private _resourceService: ResourcesService
  ) {
    this.dataSource = new MatTableDataSource();
    this.getRequestUser();
    this.getRequestAux();

    const currentYear = new Date().getFullYear();
    this.minDate = new Date(currentYear - 2, 0, 0);
    this.maxDate = new Date(currentYear + 1, 0, 0);
    translate.setDefaultLang('es');
  }

  ngOnInit(): void {
    /* this.value = (20 / 25) * 100; */
  }

  updatePaginator() {
    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator._intl.itemsPerPageLabel = data[0];
      this.paginator._intl.firstPageLabel = data[1];
      this.paginator._intl.lastPageLabel = data[2];
      this.paginator._intl.nextPageLabel = data[3];
      this.paginator._intl.previousPageLabel = data[4];
    });
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

    if (window.innerWidth <= 721) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (window.innerWidth > 721) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }

    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator._intl.itemsPerPageLabel = data[0];
      this.paginator._intl.firstPageLabel = data[1];
      this.paginator._intl.lastPageLabel = data[2];
      this.paginator._intl.nextPageLabel = data[3];
      this.paginator._intl.previousPageLabel = data[4];
    });
  }

  filterData(state: any) {
    this.selectedOpcion = state;
    let arr: any[] = [];
    arr = this.workflows.filter((e: any) => {
      return e.isCompleted == state;
    });

    this.dataSource.data = arr;
    this.dataSource.data.length > 0
      ? (this.data_empty = false)
      : (this.data_empty = true);
  }

  openDialogConfirmAction(action: any, item: any) {
    this.isLoadingForm = true;

    let dataAction = {
      action: action,
      item: item,
    };

    const dialogRef = this.dialog.open(RequestWorkflowFormComponent, {
      data: dataAction,
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        if (result.reasons == '') {
          let objAux = { isValidated: result.isValidated };
          this.isLoadingForm = false;
          this.updateRequest(item.id, objAux);
        } else {
          this.isLoadingForm = false;
          this.updateRequest(item.id, result);
        }
      }
      this.isLoadingForm = false;
    });
  }

  clearFilter() {
    this.getRequestUser();
    this.filterCreatedDate = '';
    this.filterValidatedDate = '';
    this.filterModule = '';
    this.data_empty = false;
    this.filter_empty = false;
  }

  filter() {
    let arrFilter: any[] = this.workflows;
    let dateAux: string = '';
    let arrAux: any[] = [];

    if (this.filterCreatedDate != '') {
      dateAux = this.formatDate(this.filterCreatedDate);

      for (let index = 0; index < arrFilter.length; index++) {
        if (
          arrFilter[index].created_at == dateAux &&
          arrFilter[index].isValidated != false
        ) {
          arrAux.push(arrFilter[index]);
        }
      }
      this.filterValidate(arrAux);
    } else {
      this.filterValidate(arrFilter);
    }
  }

  filterValidate(arrFilter: any[]) {
    let dateAux: string = '';
    let arrAux: any[] = [];

    if (this.filterValidatedDate != '' && arrFilter.length > 0) {
      dateAux = this.formatDate(this.filterValidatedDate);
      for (let index = 0; index < arrFilter.length; index++) {
        if (
          arrFilter[index].updated_at === dateAux &&
          arrFilter[index].isValidated != false
        ) {
          arrAux.push(arrFilter[index]);
        }
      }
      this.filterModuleFunction(arrAux);
    } else {
      this.filterModuleFunction(arrAux);
    }
  }

  filterModuleFunction(arrFilter: any[]) {
    let arrAux: any[] = [];
    if (this.filterModule != '' && arrFilter.length > 0) {
      for (let index = 0; index < arrFilter.length; index++) {
        if (arrFilter[index].module === this.filterModule) {
          arrAux.push(arrFilter[index]);
        }
      }

      this.dataSource.data = arrAux;
      this.dataSource.data.length > 0
        ? (this.filter_empty = false)
        : (this.filter_empty = true);
    } else {
      this.dataSource.data = arrAux;
      this.dataSource.data.length > 0
        ? (this.filter_empty = false)
        : (this.filter_empty = true);
    }
  }

  public async updateRequest(request: any, idRequest: any) {
    await lastValueFrom(
      this._samwfService.updateRequests(request, idRequest)
    ).then(
      (data: ResponseData) => {
        this.isLoadingForm = true;
        this._snackBar.open(data.msg, 'Cerrar', {
          duration: 3000,
        });

        this.isLoadingForm = false;
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.ngOnInit();
  }

  private async getRequestUser() {
    this.isLoading = true;
    await lastValueFrom(this._samwfService.getRequestUser('SAM001')).then(
      (data: any) => {
        this.workflows = data.response;

        this.dataSource.data =
          data.response.length > 0
            ? data.response.filter((e: any) => {
                e.created_at = e.created_at.slice(0, 10);
                e.updated_at = e.updated_at.slice(0, 10);

                return e.isCompleted == this.selectedOpcion;
              })
            : [];

        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );

    await lastValueFrom(this._samwfService.getModules()).then(
      (data: any) => {
        this.modules = data.response;
      },
      (error: HttpErrorResponse) => {
        this._resourceService.checkErrors(error);
      }
    );

    this.isLoading = false;
  }

  private async getRequestAux() {
    await lastValueFrom(this._samwfService.getAllRequests()).then(
      (data: any) => {
        this.requests = data.response;
      },
      (error: HttpErrorResponse) => console.log(error)
    );

    await lastValueFrom(this._samwfService.getModules()).then(
      (data: any) => {
        this.modules = data.response;
      },
      (error: HttpErrorResponse) => {
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }

  private formatDate(date: Date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
  }

  public applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  public onResize(event: any) {
    if (event.target.innerWidth <= 721) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (event.target.innerWidth > 721) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }
  }
}
