import {
  ChangeDetectionStrategy,
  Component,
  input,
  output
} from '@angular/core';

export interface OnboardingStep {
  readonly key: string;
  readonly label: string;
}

@Component({
  selector: 'onboarding-stepper',
  standalone: true,
  imports: [],
  templateUrl: './onboarding-stepper.html',
  styleUrl: './onboarding-stepper.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnboardingStepper {
  readonly steps = input.required<readonly OnboardingStep[]>();
  readonly currentStepIndex = input.required<number>();
  readonly completedStepIndexes = input<readonly number[]>([]);

  readonly savingDraft = input(false);
  readonly finishing = input(false);
  readonly navigationDisabled = input(false);

  readonly stepSelected = output<number>();
  readonly backClicked = output<void>();
  readonly nextClicked = output<void>();
  readonly saveDraftClicked = output<void>();
  readonly finishClicked = output<void>();
  readonly cancelClicked = output<void>();

  isFirstStep(): boolean {
    return this.currentStepIndex() === 0;
  }

  isLastStep(): boolean {
    return this.currentStepIndex() === this.steps().length - 1;
  }

  isCurrentStep(index: number): boolean {
    return index === this.currentStepIndex();
  }

  isCompletedStep(index: number): boolean {
    return this.completedStepIndexes().includes(index);
  }

  isPendingStep(index: number): boolean {
    return !this.isCurrentStep(index) && !this.isCompletedStep(index);
  }

  canOpenStep(index: number): boolean {
    if (this.navigationDisabled()) {
      return false;
    }

    return (
      index < this.currentStepIndex() ||
      this.isCompletedStep(index)
    );
  }

  selectStep(index: number): void {
    if (!this.canOpenStep(index)) {
      return;
    }

    this.stepSelected.emit(index);
  }

  requestBack(): void {
    if (this.navigationDisabled() || this.isFirstStep()) {
      return;
    }

    this.backClicked.emit();
  }

  requestNext(): void {
    if (this.navigationDisabled() || this.isLastStep()) {
      return;
    }

    this.nextClicked.emit();
  }

  requestSaveDraft(): void {
    if (this.navigationDisabled() || this.savingDraft()) {
      return;
    }

    this.saveDraftClicked.emit();
  }

  requestFinish(): void {
    if (
      this.navigationDisabled() ||
      this.finishing() ||
      !this.isLastStep()
    ) {
      return;
    }

    this.finishClicked.emit();
  }

  requestCancel(): void {
    if (this.navigationDisabled()) {
      return;
    }

    this.cancelClicked.emit();
  }
}