import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RemissionItem, RemissionStore } from '@isa/remission/data-access';
import { CheckboxComponent } from '@isa/ui/input-controls';

@Component({
  selector: 'remi-feature-remission-list-item-select',
  templateUrl: './remission-list-item-select.component.html',
  styleUrl: './remission-list-item-select.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormsModule, CheckboxComponent],
})
export class RemissionListItemSelectComponent {
  /**
   * Store for managing selected remission quantities.
   * @private
   */
  #store = inject(RemissionStore);

  /**
   * The item to display in the list.
   * Can be either a ReturnItem or a ReturnSuggestion.
   */
  item = input.required<RemissionItem>();

  /**
   * Signal indicating whether the item has stock to remit.
   * This is used to conditionally display the select component.
   */
  hasStockToRemit = input.required<boolean>();

  /**
   * Signal indicating whether remission has started.
   * Used to determine if the item can be selected or not.
   */
  remissionStarted = computed(() => this.#store.remissionStarted());

  /**
   * Computes whether to display the checkbox for selecting the item.
   * Only displays if remission has started and there is stock to remit.
   */
  displayCheckbox = computed(
    () => this.remissionStarted() && this.hasStockToRemit(),
  );

  /**
   * Computes whether the current item is selected in the remission store.
   * Checks if the item's ID exists in the selected items collection.
   */
  itemSelected = computed(() => {
    const itemId = this.item()?.id;
    return !!itemId && !!this.#store.selectedItems()?.[itemId];
  });

  /**
   * Selects the current item in the remission store.
   * Updates the selected items and quantities based on the item's ID.
   *
   * @param selected - Whether the item should be selected or not
   */
  setSelected(selected: boolean) {
    const itemId = this.item()?.id;
    if (itemId && selected) {
      this.#store.selectRemissionItem(itemId, this.item());
    }
    if (itemId && !selected) {
      this.#store.removeItem(itemId);
    }
  }
}
