import {
  ChangeDetectionStrategy,
  Component,
  contentChildren,
  input,
  linkedSignal,
} from '@angular/core';
import { StepComponent } from './step.component';
import { NgClass } from '@angular/common';

@Component({
  selector: 'app-stepper',
  imports: [NgClass],
  templateUrl: './stepper.component.html',
  styleUrl: './stepper.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class StepperComponent {
  readonly steps = contentChildren(StepComponent);
  readonly initialStepIndex = input(0);
  readonly disabled = input(false);
  readonly currentStepIndex = linkedSignal(() => this.initialStepIndex());

  next() {
    if (this.disabled()) return;

    const currentSteps = this.steps();
    const currentIndex = this.currentStepIndex();
    if (currentIndex < currentSteps.length - 1) {
      const currentStep = currentSteps[currentIndex];
      if (currentStep.isValid()) {
        this.currentStepIndex.set(currentIndex + 1);
      }
    }
  }

  previous() {
    if (this.disabled()) return;

    const currentIndex = this.currentStepIndex();
    if (currentIndex > 0) {
      this.currentStepIndex.set(currentIndex - 1);
    }
  }

  goToStep(index: number) {
    if (this.disabled()) return;

    const targetIndex = index;
    // Only allow navigating to completed steps or the current one
    if (targetIndex < this.currentStepIndex()) {
      this.currentStepIndex.set(targetIndex);
    }
  }
}
