import { UikitFieldComponent } from '@/uikit';
import { DOCUMENT } from '@angular/common';
import { Component, Inject, computed, Input } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { Select } from 'primeng/select';
import { Observable } from 'rxjs';
import { AbstractSelectComponent, ISelectItem } from '../abstractClasses';
import { LOCAL_ENUMS } from './constants';
import { TLocalEnum } from './models';

@Component({
  selector: 'app-enum-select',
  templateUrl: './select.component.html',
  imports: [UikitFieldComponent, Select, ReactiveFormsModule],
})
export class EnumSelectComponent extends AbstractSelectComponent<ISelectItem, ISelectItem[]> {
  @Input() type!: TLocalEnum;
  @Input() customLabel?: string;

  constructor(@Inject(DOCUMENT) private readonly document: Document) {
    super();
  }

  label = computed(() => this.customLabel ?? LOCAL_ENUMS[this.type].label);

  override getDataService() {
    return new Observable<ISelectItem[]>((observer) => {
      return observer.next(LOCAL_ENUMS[this.type].items);
    });
  }

  ngOnInit() {
    this.getData();
  }

  overlayOptions() {
    return {
      autoZIndex: true,
      baseZIndex: this.overlayBaseZIndex(),
    };
  }

  overlayBaseZIndex() {
    const drawers = Array.from(this.document.body.querySelectorAll('.p-drawer,[data-pc-name="drawer"]')) as HTMLElement[];
    const zIndexes = drawers
      .map((drawer) => Number.parseInt(drawer.style.zIndex || '0', 10))
      .filter((zIndex) => Number.isFinite(zIndex) && zIndex > 0);

    return zIndexes.length ? Math.max(...zIndexes) + 2 : 1000;
  }
}
