import { ChangeDetectionStrategy, Component, computed, inject, input } from '@angular/core';
import { ChipsComponent } from './chips.component';

/**
 * A selectable chip option component that integrates with ChipsComponent.
 * This component represents an individual selectable item within a chips group.
 *
 * @template T - The type of value that this chip option can hold
 *
 * @example
 * ```html
 * <ui-chips [(ngModel)]="selected">
 *   <ui-chip-option [value]="1">Option 1</ui-chip-option>
 *   <ui-chip-option [value]="2">Option 2</ui-chip-option>
 * </ui-chips>
 * ```
 */
@Component({
  selector: 'ui-chip-option',
  template: `<ng-content></ng-content>`,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { '[class]': '["ui-chip-option", selectedClass()]', '(click)': 'toggle()' },
})
export class ChipOptionComponent<T> {
  /** Reference to the parent ChipsComponent */
  private host = inject(ChipsComponent, { host: true });

  /**
   * Computed signal that determines if this option is currently selected.
   * Updates when the parent chips component value changes.
   */
  selected = computed(() => {
    this.host.value();
    return this.host.isSelected(this.value());
  });

  /**
   * Computed signal that returns the CSS class for the selected state.
   * Returns 'ui-chip-option__selected' when the option is selected, empty string otherwise.
   */
  selectedClass = computed(() => {
    return this.selected() ? 'ui-chip-option__selected' : '';
  });

  /**
   * The value associated with this chip option.
   * This is a required input that must be provided when using the component.
   */
  value = input.required<T>();

  /**
   * Toggles the selection state of this chip option.
   * Delegates the selection handling to the parent ChipsComponent.
   * Prevents toggling if the parent ChipsComponent is disabled.
   */
  toggle(): void {
    if (this.host.disabled()) {
      return;
    }
    this.host.select(this.value());
  }
}
