import { Component, ViewChild, AfterViewInit, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';
import { TasksJSONInterface } from 'src/app/interfaces/samwf/tasks-json-interface';
import { MatSnackBar } from '@angular/material/snack-bar';
import { TaskModuleFormComponent } from './task-module-form/task-module-form.component';
import { MatSort } from '@angular/material/sort';
import { ResourcesService } from 'src/app/services/resources/resources.service';
import { AlertData } from 'src/app/interfaces/alert.interface';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';
import { ResponseData } from 'src/app/interfaces/response-data';

@Component({
  selector: 'app-tasks-module',
  templateUrl: './tasks-module.component.html',
  styleUrls: ['./tasks-module.component.css'],
})
export class TasksModuleComponent implements AfterViewInit {
  loading: Boolean = false;
  tasks: any[] = [];
  data_empty = false;
  filter_empty = false;

  displayedColumns: string[] = [
    'name_task',
    'module',
    'workflow',
    'isAvailable',
    'notification',
    'actions',
  ];

  minDate: Date;
  maxDate: Date;
  modules: any[] = [];
  filterSendDate: any;
  filterModule: any;
  workflowsDataBase: any[] = [];

  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;

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

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

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

    if (window.innerWidth <= 818) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (window.innerWidth > 818) {
      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];
    });
  }

  ngOnInit(): void {}

  backToWorkflows() {
    this.router.navigate(['workflow']);
  }

  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];
    });
  }

  async openDialogTaskForm(action: string, item: any) {
    this.isLoadingForm = true;
    let dataAux = {
      action: action,
      item: item,
      workflows: this.workflowsDataBase,
      modules: this.modules,
    };
    const dialogRef = this.dialog.open(TaskModuleFormComponent, {
      data: dataAux,
      width: '800px',
      disableClose: true,
    });

    dialogRef.afterClosed().subscribe((result: any) => {
      if (result) {
        if (action == 'Registrar') {
          this.registerTask(result);
        } else {
          console.log(result);
          this.editTask(item.id, result);
        }
      }
      this.isLoadingForm = false;
    });
  }

  async disableTask(idTask: any) {
    await lastValueFrom(this._samwfService.disableTaskModule(idTask)).then(
      (data: any) => {
        if (!data.error) {
          this._snackBar.open('!Actualización de tarea exitoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: any) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.getTasks();
  }

  private async getWorkflows() {
    await lastValueFrom(this._samwfService.getWorkflows()).then(
      (data: ResponseData) => {
        this.workflowsDataBase = data.response;
      },
      (error: any) => {
        this._resourceService.checkErrors(error);
      }
    );
  }

  private async registerTask(task: TasksJSONInterface) {
    await lastValueFrom(this._samwfService.registerTask(task)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._snackBar.open('!Registro de tarea existoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: any) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.getTasks();
  }

  private async editTask(idTask: any, task: TasksJSONInterface) {
    await lastValueFrom(this._samwfService.updateTask(idTask, task)).then(
      (data: ResponseData) => {
        if (!data.error) {
          this._snackBar.open('!Modificación de tarea existoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: any) => {
        this._resourceService.checkErrors(error);
      }
    );
    this.getTasks();
  }

  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('-');
  }

  private async getTasks() {
    this.isLoading = true;
    await lastValueFrom(this._samwfService.getTasks()).then(
      (data: ResponseData) => {
        this.loading = false;

        this.dataSource.data = data.response;
        this.tasks = data.response;

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

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

        this.loading = true;
        this._snackBar.open(
          'Continuamos buscando la información, espere un momento.',
          'Cerrar',
          { duration: 3000 }
        );
      }
    );

    this.isLoading = false;
  }

  public async alert(type: string, data: any = null) {
    this.isLoadingForm = true;
    let info: AlertData = {} as AlertData;
    switch (type) {
      case 'DT':
        info = {
          icon: 'warning',
          title:
            data.isAvailable == true ? 'Inhabilitar Tarea' : 'Habilitar tarea',
          description:
            data.isAvailable == true
              ? '¿Está seguro de inhabilitar esta tarea?'
              : '¿Está seguro de habilitar esta tarea?',
        };
        break;
    }

    const dialogRef = this.dialog.open(AlertComponent, {
      data: info,
      disableClose: true,
      width: '350px',
    });
    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        switch (type) {
          case 'DT':
            this.disableTask(data.id);
            break;
        }
      }
      this.isLoadingForm = false;
    });
  }

  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 <= 818) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (event.target.innerWidth > 818) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }
  }
}
