import {
  ChangeDetectionStrategy,
  Component,
  input,
  linkedSignal,
  inject,
  OnDestroy,
} from '@angular/core';
import { Item } from '@isa/catalogue/data-access';
import { FormsModule } from '@angular/forms';
import { CheckboxComponent } from '@isa/ui/input-controls';
import { RewardCatalogStore } from '@isa/checkout/data-access';

@Component({
  selector: 'reward-list-item-select',
  templateUrl: './reward-list-item-select.component.html',
  styleUrl: './reward-list-item-select.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormsModule, CheckboxComponent],
})
export class RewardListItemSelectComponent implements OnDestroy {
  #store = inject(RewardCatalogStore);

  item = input.required<Item>();

  itemSelected = linkedSignal(() => {
    const itemId = this.item()?.id;
    return !!itemId && !!this.#store.selectedItems()?.[itemId];
  });

  setSelected(selected: boolean) {
    const itemId = this.item()?.id;
    if (itemId && selected) {
      this.#store.selectItem(itemId, this.item());
    }
    if (itemId && !selected) {
      this.#store.removeItem(itemId);
    }
  }

  ngOnDestroy() {
    const itemId = this.item().id;
    this.#store.removeItem(itemId);
  }
}
