import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  model,
  resource,
  signal,
  viewChild,
} from '@angular/core';
import { FormsModule, NgModel } from '@angular/forms';
import { RemissionReasonService, ReturnItem } from '@isa/remission/data-access';
import {
  DropdownButtonComponent,
  DropdownOptionComponent,
} from '@isa/ui/input-controls';
import { QuantityAndReason } from './select-remi-quantity-and-reason-dialog.component';
import { ReturnValue } from '@isa/common/data-access';
import { provideIcons } from '@ng-icons/core';
import { isaActionChevronDown, isaActionChevronUp } from '@isa/icons';

@Component({
  selector: 'remi-quantity-and-reason-item',
  templateUrl: './quantity-and-reason-item.component.html',
  styleUrls: ['./quantity-and-reason-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [DropdownButtonComponent, DropdownOptionComponent, FormsModule],
  providers: [provideIcons({ isaActionChevronDown, isaActionChevronUp })],
})
export class QuantityAndReasonItemComponent {
  #reasonService = inject(RemissionReasonService);

  readonly control = viewChild.required<NgModel>('#model');

  showNumberInput = signal(false);

  position = input.required<number>();

  canAddResult = input<ReturnValue<ReturnItem>>();

  quantityAndReason = model.required<QuantityAndReason>();

  dropdownLabel = computed(() => {
    const reason = this.quantityAndReason().reason;
    return reason !== '' ? reason : 'Remigrund';
  });

  reasonResource = resource({
    loader: async ({ abortSignal }) => {
      return this.#reasonService.fetchReturnReasons(abortSignal);
    },
  });

  quantity = computed(() => {
    const quantity = this.quantityAndReason().quantity;
    return quantity !== undefined && quantity >= 1 ? quantity : undefined;
  });

  setQuantity(quantity: number): void {
    this.quantityAndReason.update((qar) => ({
      ...qar,
      quantity,
    }));
  }

  setReason(reason: string): void {
    this.quantityAndReason.update((qar) => ({
      ...qar,
      reason,
    }));
  }
}
