import {
  Component,
  input,
  output,
  viewChild,
  ElementRef,
  effect,
  inject,
  ChangeDetectionStrategy,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TextButtonComponent } from '@isa/ui/buttons';
import {
  TextFieldComponent,
  InputControlDirective,
  TextFieldClearComponent,
} from '@isa/ui/input-controls';
import { BonRedemptionStore } from '@isa/crm/data-access';

/**
 * Smart component for Bon number input field.
 *
 * Injects BonRedemptionStore for state management.
 *
 * Features:
 * - Input field with validation
 * - Search button (when no result) or clear button (when result/error)
 * - Success/error message display
 * - Enter key support for validation
 *
 * @example
 * <crm-bon-input-field
 *   [cardCode]="cardCode"
 *   (validate)="onValidate()"
 *   (clearForm)="onClear()" />
 */
@Component({
  selector: 'crm-bon-input-field',
  imports: [
    FormsModule,
    TextButtonComponent,
    TextFieldComponent,
    TextFieldClearComponent,
    InputControlDirective,
  ],
  templateUrl: './bon-input-field.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BonInputFieldComponent {
  /**
   * Store for accessing state
   */
  readonly store = inject(BonRedemptionStore);

  /**
   * Active card code (required for validation)
   */
  readonly cardCode = input<string | undefined>(undefined);

  /**
   * Emits when validation should be triggered
   */
  readonly validate = output<void>();

  /**
   * Emits when form should be cleared/reset
   */
  readonly clearForm = output<void>();

  /**
   * Reference to the input element for focusing
   */
  inputRef = viewChild.required<ElementRef<HTMLInputElement>>('bonInput');

  /**
   * Effect to focus input when reset is called
   */
  constructor() {
    effect(() => {
      // Focus when both error and validBon are false (after reset)
      if (!this.store.hasError() && !this.store.hasValidBon()) {
        const inputEl = this.inputRef()?.nativeElement;
        if (inputEl && document.activeElement !== inputEl) {
          setTimeout(() => inputEl.focus(), 0);
        }
      }
    });
  }

  /**
   * Handle Bon number input changes
   */
  onBonNumberChange(value: string): void {
    this.store.setBonNumber(value);
  }

  /**
   * Handle validation trigger
   */
  onValidate(): void {
    this.validate.emit();
  }

  /**
   * Handle reset/clear action
   */
  onReset(): void {
    this.clearForm.emit();
  }
}
