import { Component, NgZone, inject, OnInit } from '@angular/core';
import { ActivatedRoute, Data, ParamMap, Router, RouterModule } from '@angular/router';
import { combineLatest, filter, Observable, Subscription, tap, map } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { HttpResponse } from '@angular/common/http';

import SharedModule from 'app/shared/shared.module';
import { sortStateSignal, SortDirective, SortByDirective, type SortState, SortService } from 'app/shared/sort';
import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { SORT, ITEM_DELETED_EVENT, DEFAULT_SORT_DATA } from 'app/config/navigation.constants';
import { IUnit } from '../unit.model';
import { EntityArrayResponseType, UnitService } from '../service/unit.service';
import { UnitDeleteDialogComponent } from '../delete/unit-delete-dialog.component';

import { UnitTypeService } from 'app/entities/unit-type/service/unit-type.service';
import { IUnitType } from 'app/entities/unit-type/unit-type.model';
import { UnitSearchFormService, UnitSearchFormGroup } from './unit-search-form.service';

@Component({
  standalone: true,
  selector: 'jhi-unit',
  templateUrl: './unit.component.html',
  imports: [
    RouterModule,
    FormsModule,
    ReactiveFormsModule,
    SharedModule,
    SortDirective,
    SortByDirective,
    DurationPipe,
    FormatMediumDatetimePipe,
    FormatMediumDatePipe,
  ],
})
export class UnitComponent implements OnInit {
  subscription: Subscription | null = null;
  units?: IUnit[];
  isLoading = false;

  sortState = sortStateSignal({});

  unitTypesSharedCollection: IUnitType[] = [];

  public router = inject(Router);
  protected unitTypeService = inject(UnitTypeService);
  protected unitService = inject(UnitService);
  protected unitSearchFormService = inject(UnitSearchFormService);
  protected activatedRoute = inject(ActivatedRoute);
  protected sortService = inject(SortService);
  protected modalService = inject(NgbModal);
  protected ngZone = inject(NgZone);

  searchForm: UnitSearchFormGroup = this.unitSearchFormService.createUnitSearchFormGroup();
  trackId = (_index: number, item: IUnit): number => this.unitService.getEntityIdentifier(item);

  compareUnitType = (o1: IUnitType | null, o2: IUnitType | null): boolean =>
    this.unitTypeService.compareEntity(o1, o2);
    
  ngOnInit(): void {
    this.subscription = combineLatest([this.activatedRoute.queryParamMap, this.activatedRoute.data])
      .pipe(
        tap(([params, data]) => this.fillComponentAttributeFromRoute(params, data)),
        tap(() => {
          if (!this.units || this.units.length === 0) {
            this.load();
          }
        }),
      )
      .subscribe();
      
    this.loadRelationshipsOptions();
  }

  delete(unit: IUnit): void {
    const modalRef = this.modalService.open(UnitDeleteDialogComponent, { size: 'lg', backdrop: 'static' });
    modalRef.componentInstance.unit = unit;
    // unsubscribe not needed because closed completes on modal close
    modalRef.closed
      .pipe(
        filter(reason => reason === ITEM_DELETED_EVENT),
        tap(() => this.load()),
      )
      .subscribe();
  }

  onSearch(): void {
	  this.load();
  }
  
  load(): void {
    this.queryBackend().subscribe({
      next: (res: EntityArrayResponseType) => {
        this.onResponseSuccess(res);
      },
    });
  }

  navigateToWithComponentValues(event: SortState): void {
    this.handleNavigation(event);
  }

  protected fillComponentAttributeFromRoute(params: ParamMap, data: Data): void {
    this.sortState.set(this.sortService.parseSortParam(params.get(SORT) ?? data[DEFAULT_SORT_DATA]));
  }

  protected onResponseSuccess(response: EntityArrayResponseType): void {
    const dataFromBody = this.fillComponentAttributesFromResponseBody(response.body);
    this.units = this.refineData(dataFromBody);
  }

  protected refineData(data: IUnit[]): IUnit[] {
    const { predicate, order } = this.sortState();
    return predicate && order ? data.sort(this.sortService.startSort({ predicate, order })) : data;
  }

  protected fillComponentAttributesFromResponseBody(data: IUnit[] | null): IUnit[] {
    return data ?? [];
  }

  protected queryBackend(): Observable<EntityArrayResponseType> {
    this.isLoading = true;
    const queryObject: any = {
      eagerload: true,
      sort: this.sortService.buildSortParam(this.sortState()),
    };
    
    const searchModel = this.unitSearchFormService.getUnit(this.searchForm);
    this.unitSearchFormService.applySearchConditionsToQueryObject(queryObject, searchModel);
	
    return this.unitService.queryByCriteria(queryObject).pipe(tap(() => (this.isLoading = false)));
  }

  protected handleNavigation(sortState: SortState): void {
    const queryParamsObj = {
      sort: this.sortService.buildSortParam(sortState),
    };

    this.ngZone.run(() => {
      this.router.navigate(['./'], {
        relativeTo: this.activatedRoute,
        queryParams: queryParamsObj,
      });
    });
  }
  
  protected loadRelationshipsOptions(): void {
    this.unitTypeService
      .query()
      .pipe(map((res: HttpResponse<IUnitType[]>) => res.body ?? []))
      .subscribe((unitTypes: IUnitType[]) => (this.unitTypesSharedCollection = unitTypes));
  }
}
