import { Component, Input, OnInit, inject } from '@angular/core';
import { Observable, tap } from 'rxjs';
import { sortStateSignal, SortDirective, SortByDirective, type SortState, SortService } from 'app/shared/sort';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import SharedModule from 'app/shared/shared.module';

import { ResilientEnvironmentService, EntityArrayResponseType } from 'app/resilient/resilient-environment/service/resilient-environment.service';
import { PeriodService } from 'app/entities/period/service/period.service';
import { IPeriod } from 'app/entities/period/period.model';
import { PeriodSelectorSearchFormService, PeriodSelectorSearchFormGroup } from './period-selector-search-form.service';

@Component({
  selector: 'app-period-selector',
  standalone: true,
  imports: [SharedModule,FormsModule, ReactiveFormsModule],
  templateUrl: './period-selector.component.html',
  styleUrl: './period-selector.component.scss'
})
export class PeriodSelectorComponent implements OnInit {
  @Input() defaultSelectedPeriodId : any;  // The initial selected period
  
  periods?: IPeriod[];
  selectedPeriod?: IPeriod;
  isLoading = false;
  
  sortState = sortStateSignal({});
  
  protected periodService = inject(PeriodService);
  protected environmentService = inject(ResilientEnvironmentService);
  protected sortService = inject(SortService);
  protected periodSelectorSearchFormService = inject(PeriodSelectorSearchFormService);
  
  searchForm: PeriodSelectorSearchFormGroup = this.periodSelectorSearchFormService.createPeriodSelectorSearchFormGroup();
  
  comparePeriod = (o1: IPeriod | null, o2: IPeriod | null): boolean =>
    this.periodService.compareEntity(o1, o2);

  ngOnInit(): void {
    console.log(this.defaultSelectedPeriodId);
    
    if (!this.periods || this.periods.length === 0) {
      this.load();
    }
  }
  
  onSearch(): void {
  }
  
  load(): void {
    this.queryBackend().subscribe({
      next: (res: EntityArrayResponseType) => {
        this.onResponseSuccess(res);
      },
    });
  }
  
  onChange(event: any): void {
    this.environmentService.selectPeriod(this.selectedPeriod??null);
  }
  
  protected queryBackend(): Observable<EntityArrayResponseType> {
    this.isLoading = true;
    const queryObject: any = {
      eagerload: true,
      sort: this.sortService.buildSortParam(this.sortState()),
    };
    return this.periodService.query(queryObject).pipe(tap(() => (this.isLoading = false)));
  }
  
  protected onResponseSuccess(response: EntityArrayResponseType): void {
    const dataFromBody = this.fillComponentAttributesFromResponseBody(response.body);
    this.periods = this.refineData(dataFromBody);
    if (this.periods.length >= 1) {
      if (this.defaultSelectedPeriodId) {
        // Select the provided default Period
        this.selectedPeriod = this.periods.find(period => period.id === this.defaultSelectedPeriodId) || undefined;
      } else {
        // Select the first OR the default when provided
        this.selectedPeriod = this.periods[0]; 
      }
      
      this.environmentService.selectPeriod(this.selectedPeriod ?? null);
      if (this.selectedPeriod) {
        this.searchForm.patchValue({ periodId: this.selectedPeriod.id });
      }
    }
  }
  
  protected refineData(data: IPeriod[]): IPeriod[] {
    const { predicate, order } = this.sortState();
    return predicate && order ? data.sort(this.sortService.startSort({ predicate, order })) : data;
  }
  
  protected fillComponentAttributesFromResponseBody(data: IPeriod[] | null): IPeriod[] {
    return data ?? [];
  }
}
