import { CommonModule } from '@angular/common';
import { Component, Input, model } from '@angular/core';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ButtonModule } from 'primeng/button';
import { InputNumber } from 'primeng/inputnumber';

@Component({
  selector: 'app-uikit-counter',
  templateUrl: './uikit-counter.component.html',
  styleUrls: ['./uikit-counter.component.scss'],
  standalone: true,
  imports: [CommonModule, ButtonModule, FormsModule, ReactiveFormsModule, FormsModule, InputNumber],
})
export class UikitCounterComponent {
  @Input() control = new FormControl<number>(0);
  @Input() min: number | null = null;
  @Input() max: number | null = null;
  @Input() step = 1;
  @Input() disabled = false;

  value = model(0);

  clamp(v: number): number {
    if (this.min !== null && v < this.min) return this.min;
    if (this.max !== null && v > this.max) return this.max;
    return v;
  }

  setValue(v: number) {
    const clamped = this.clamp(v);
    if (clamped !== this.value()) {
      this.control?.setValue(clamped);
      this.value.set(clamped);
    }
  }

  increase() {
    if (this.disabled) return;
    this.setValue(this.value() + this.step);
  }

  decrease() {
    if (this.disabled) return;
    this.setValue(this.value() - this.step);
  }

  onInput(e: Event) {
    const v = (e.target as HTMLInputElement).value;
    const n = Number(v);
    if (!Number.isNaN(n)) {
      this.setValue(n);
    }
  }
}
