import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ProcessManagementService } from '../../../../services/process-management/process-management.service';
import { ResourcesService } from '../../../../services/resources.service';
import { InternationalizationService } from '../../../../services/internationalization/internationalization.service';
import {
  Task,
  ResponseDataTask,
} from '../../../../interfaces/process-managementv/workflow-management.interface';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-task-details',
  templateUrl: './task-details.component.html',
  styleUrl: './task-details.component.css',
  standalone: false,
})
export class TaskDetailsComponent implements OnInit {
  public isLoading: boolean = false;
  public task: Task | null = null;

  constructor(
    public dialogRef: MatDialogRef<TaskDetailsComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { idTask: number },
    private _processManagementService: ProcessManagementService,
    private _resourcesService: ResourcesService,
    public interService: InternationalizationService
  ) {}

  async ngOnInit() {
    await this.getTaskDetails();
  }

  private async getTaskDetails() {
    this.isLoading = true;
    const user: string = this._resourcesService.getUser();
    const line: number = this._resourcesService.getLineNumber();

    await lastValueFrom(
      this._processManagementService.getTaskById(
        this.data.idTask.toString(),
        user,
        line
      )
    ).then(
      (responseData: ResponseDataTask) => {
        if (!responseData.error) {
          console.log(responseData);

          this.task = responseData.response;
        } else {
          this._resourcesService.openSnackBar(`${responseData.msg}`);
        }
      },
      (httpErrorResponse: HttpErrorResponse) => {
        this._resourcesService.checkErrors(httpErrorResponse);
      }
    );
    this.isLoading = false;
  }

  public close() {
    this.dialogRef.close();
  }

  public formatDate(dateString: string): string {
    if (!dateString) return this.interService.get('na');
    
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = Math.abs(now.getTime() - date.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays <= 7) {
      if (diffDays === 0) return this.interService.get('hoy');
      if (diffDays === 1) return this.interService.get('hace_1_dia');
      return this.interService.get('hace_dias').replace('{0}', diffDays.toString());
    } else {
      return date.toLocaleDateString('es-ES');
    }
  }
}
