import {
  ChangeDetectionStrategy,
  Component,
  computed,
  ElementRef,
  inject,
  input,
  signal,
} from '@angular/core';
import { Highlightable } from '@angular/cdk/a11y';
import { QuantityControlComponent } from './quantity-control.component';

@Component({
  selector: 'shared-quantity-control-option',
  templateUrl: './quantity-control-option.component.html',
  styleUrls: ['./quantity-control-option.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [],
  host: {
    '[class]':
      '["quantity-control-option", activeClass(), selectedClass(), disabledClass()]',
    'role': 'option',
    '[id]': 'id()',
    '[attr.aria-selected]': 'selected()',
    '[attr.tabindex]': '-1',
    '[attr.data-what]': '"quantity-control-option"',
    '[attr.data-which]': 'value()',
    '(click)': 'select()',
  },
})
export class QuantityControlOptionComponent implements Highlightable {
  private host = inject(QuantityControlComponent);

  /**
   * Reference to the host element for scrolling
   */
  elementRef = inject(ElementRef<HTMLElement>);

  /**
   * Unique ID for this option (for ARIA)
   */
  id = input.required<string>();

  /**
   * Option value - can be a number or 'edit'
   */
  value = input.required<number | 'edit'>();

  /**
   * Active state (keyboard highlight)
   */
  active = signal(false);

  /**
   * Disabled state
   */
  disabled?: boolean;

  /**
   * Whether this option is selected
   */
  selected = computed(() => {
    const val = this.value();
    // 'edit' option is never selected
    if (val === 'edit') {
      return false;
    }
    return this.host.value() === val;
  });

  /**
   * CSS class for active state
   */
  activeClass = computed(() => (this.active() ? 'active' : ''));

  /**
   * CSS class for selected state
   */
  selectedClass = computed(() => (this.selected() ? 'selected' : ''));

  /**
   * CSS class for disabled state
   */
  disabledClass = computed(() => (this.disabled ? 'disabled' : ''));

  setActiveStyles() {
    this.active.set(true);
  }

  setInactiveStyles() {
    this.active.set(false);
  }

  /**
   * Handle option selection
   */
  select() {
    if (this.disabled) {
      return;
    }

    const val = this.value();
    if (val === 'edit') {
      // Open edit mode
      this.host.enterEditMode();
    } else {
      // Select the numeric value
      this.host.selectValue(val);
    }
  }
}
