import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CallbackResult, ListResponseArgs } from '@isa/common/data-access';
import { injectTabId } from '@isa/core/tabs';
import {
  ReceiptListItem,
  ReturnSearchStatus,
  ReturnSearchStore,
} from '@isa/oms/data-access';
import { ReturnTaskListComponent } from '@isa/oms/shared/task-list';
import {
  FilterService,
  SearchBarInputComponent,
  FilterInputMenuButtonComponent,
} from '@isa/shared/filter';
import { IconButtonComponent } from '@isa/ui/buttons';
import { TooltipIconComponent } from '@isa/ui/tooltip';

@Component({
  selector: 'oms-feature-return-search-main',
  templateUrl: './return-search-main.component.html',
  styleUrls: ['./return-search-main.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    SearchBarInputComponent,
    IconButtonComponent,
    FilterInputMenuButtonComponent,
    ReturnTaskListComponent,
    TooltipIconComponent,
  ],
})
export class ReturnSearchMainComponent {
  #route = inject(ActivatedRoute);
  #router = inject(Router);

  private _processId = injectTabId();
  private _filterService = inject(FilterService);
  private _returnSearchStore = inject(ReturnSearchStore);

  private _entity = computed(() => {
    const processId = this._processId();
    if (processId) {
      return this._returnSearchStore.getEntity(processId);
    }
    return undefined;
  });

  entityPending = computed(() => {
    return this._entity()?.status === ReturnSearchStatus.Pending;
  });

  filterInputs = computed(() =>
    this._filterService.inputs().filter((input) => input.group === 'filter'),
  );

  // TODO: Suche als Provider in FilterService auslagern (+ Cancel Search, + Fetching Status)
  async onSearch() {
    const processId = this._processId();
    if (processId) {
      this._filterService.commit();
      this._returnSearchStore.search({
        processId,
        query: this._filterService.query(),
        clear: true,
        cb: this.onSearchCb,
      });
    }
  }

  onSearchCb = ({
    data,
  }: CallbackResult<ListResponseArgs<ReceiptListItem>>) => {
    if (data) {
      if (data.result.length === 1) {
        return this.navigate(['receipt', data.result[0].id]);
      }

      return this.navigate(['receipts']);
    }
  };

  navigate(path: (string | number)[]) {
    this.#router.navigate(path, {
      relativeTo: this.#route,
      queryParams: this._filterService.queryParams(),
    });
  }
}
