import { Router } from '@angular/router';

import { orderBy, State } from '@progress/kendo-data-query';
import { NgxSpinnerComponent, NgxSpinnerService } from 'ngx-spinner';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { Component, EventEmitter, Input, OnInit, Output, inject } from '@angular/core';
import { DataStateChangeEvent, GridDataResult, RowArgs, GridComponent, SelectionDirective, CheckboxColumnComponent, ColumnComponent } from '@progress/kendo-angular-grid';

import { AlertService } from '../alert/alert.service';
import { StatusSetRemarkComponent } from './statussetremark.component';
import { AuthModuleService } from '../../../providers/authmodule/authmodule.service';

@Component({
  standalone: true,
  selector: 'auth-pndg-detail',
  templateUrl: './authpndgdetail.component.html',
  imports: [GridComponent, SelectionDirective, NgxSpinnerComponent, CheckboxColumnComponent, ColumnComponent]
})
export class AuthPendingDetailComponent implements OnInit
{
  private readonly router = inject(Router);
  private readonly modalService = inject(NgbModal);
  private readonly service = inject(AuthModuleService);
  private readonly alertService = inject(AlertService);
  private readonly spinnerService = inject(NgxSpinnerService);

  @Input() public fromParent: { moduleId: string; statusToRead: number; statusToUpdate: number; processName: string; moduleName: string; };
  @Output() public okayClicked: EventEmitter<any> = new EventEmitter();
  @Input() set setHeight(value: number) 
  {
    value = value < 300 ? 300 : value;
    this.height = 'height: ' + (value - 112) + 'px;';
    this.gridHeight = 'max-height: ' + (value - 130) + 'px;';
  };

  public columns: any[] = [];
  public gridView: GridDataResult;
  public loading: boolean = false;
  public processName: string = '';
  public childWindowOpened = false;
  public selectedIds: number[] = [];
  public statusToUpdate: number = 0;
  public width: string = 'width: 800px;';
  public height: string = 'height: 373px;';
  public gridHeight: string = 'max-height: 355px;';
  public state: State = { sort: [{ field: 'name', dir: undefined }] };
  public selectedKeys(context: RowArgs): number { return context.dataItem.Id; };

  private data: any[] = [];
  private moduleId: string = '';
  private statusToRead: number = 0;
  private moduleName: string = '';

  ngOnInit(): void
  {
    this.moduleId = this.fromParent.moduleId || '';
    this.moduleName = this.fromParent.moduleName || '';
    this.processName = this.fromParent.processName || '';
    this.statusToRead = +(this.fromParent.statusToRead || 0);
    this.statusToUpdate = +(this.fromParent.statusToUpdate || 0);

    this.loadData();
  }

  private reloadData(): void
  {
    this.gridView = { data: orderBy(this.data, this.state.sort), total: this.data.length };
  }

  private loadData(): void
  {
    this.alertService.clear();
    if (!this.service.currentUserValue)
    {
      this.router.navigate(['/login']);
      return;
    }

    const params = {
      status: this.statusToRead,
      moduleId: this.moduleId
    };
    this.spinnerService.show();
    this.service.getAuthDetails(params).subscribe(
      {
        next: (resp: any) =>
        {
          this.spinnerService.hide();
          if (resp.returnStatus === 200)
          {
            this.loading = false;
            this.data = resp.data || [];
            this.columns = resp.columns || [];

            this.reloadData();
          }
          else
          {
            this.alertService.error(resp.returnMessage);
          }
        },
        error: (errorMessage: string) =>
        {
          this.loading = false;
          this.spinnerService.hide();
          this.alertService.error(errorMessage);
        }
      });
  }

  public dataStateChange(state: DataStateChangeEvent): void
  {
    this.state = state;
    this.reloadData();
  }

  public okay(): void
  {
    const params = {
      ids: this.selectedIds,
      moduleId: this.moduleId,
      status: this.statusToUpdate,
      remarks: `${this.processName} ${this.moduleName}`
    };
    this.okayClicked.emit(params);
  }

  public deactivate(): void
  {
    const modalOptions: NgbModalOptions =
    {
      centered: true,
      backdrop: 'static',
      windowClass: 'always-ontop',
      backdropClass: 'customBackdrop'
    };

    this.childWindowOpened = true;
    const modalRef = this.modalService.open(StatusSetRemarkComponent, modalOptions);
    modalRef.result.then((result) =>
    {
      this.childWindowOpened = false;
      if (result && result !== false)
      {
        const params = {
          remarks: result,
          ids: this.selectedIds,
          moduleId: this.moduleId,
          status: this.statusToUpdate
        };

        this.okayClicked.emit(params);
      }
    },
      () =>
      {
        this.childWindowOpened = false;
      }
    );
  }

  public reject(): void
  {
    const modalOptions: NgbModalOptions =
    {
      centered: true,
      backdrop: 'static',
      windowClass: 'always-ontop',
      backdropClass: 'customBackdrop'
    };

    this.childWindowOpened = true;
    const modalRef = this.modalService.open(StatusSetRemarkComponent, modalOptions);
    modalRef.result.then((result) =>
    {
      this.childWindowOpened = false;
      if (result && result !== false)
      {
        const params = {
          remarks: result,
          ids: this.selectedIds,
          moduleId: this.moduleId,
          status: 2
        };

        this.okayClicked.emit(params);
      }
    },
      () =>
      {
        this.childWindowOpened = false;
      }
    );
  }

  public close(): void
  {
    this.okayClicked.emit(false);
  }
}
