import { Component, ChangeDetectionStrategy, OnInit, OnDestroy } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { BranchSelectorComponent } from '@shared/components/branch-selector';
import { AbstractUiFilterInputDirective } from '@shared/components/filter';
import { BranchDTO } from '@generated/swagger/checkout-api';
import { Subscription } from 'rxjs';

@Component({
  selector: 'page-order-branch-id-input',
  templateUrl: 'order-branch-id-input.component.html',
  styleUrls: ['order-branch-id-input.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [BranchSelectorComponent, ReactiveFormsModule],
})
export class OrderBranchIdInputComponent extends AbstractUiFilterInputDirective implements OnInit, OnDestroy {
  control = new FormControl<BranchDTO>({});

  private _subscriptions = new Subscription();

  constructor() {
    super();
  }

  ngOnInit() {
    this.control.setValue({ id: Number(this.value) });

    const uiInputChangesSub = this.uiInput?.changes?.subscribe((changes) => {
      const controlValue = this.control?.value?.id;
      const changesValue = Number(changes?.target?.value);
      if (controlValue !== changesValue) {
        this.control.setValue(changesValue && !isNaN(changesValue) ? { id: changesValue } : undefined);
      }
    });

    const onInputChangeSub = this.onUiInputChange$.subscribe((input) => {
      const controlValue = this.control?.value?.id;
      const inputValue = Number(input?.value);
      if (controlValue !== inputValue) {
        this.control.setValue(inputValue && !isNaN(inputValue) ? { id: inputValue } : undefined);
      }
    });

    const onControlValueChangeSub = this.control.valueChanges.subscribe((value) => {
      if (!value) {
        this.setValue(undefined);
      } else if (this.value !== String(value?.id)) {
        this.setValue(String(value?.id));
      }
    });

    this._subscriptions.add(uiInputChangesSub);
    this._subscriptions.add(onInputChangeSub);
    this._subscriptions.add(onControlValueChangeSub);
  }

  ngOnDestroy() {
    this._subscriptions.unsubscribe();
  }
}
