// stores/SignupStepsStore.ts
import { makeAutoObservable } from 'mobx';

import MobileSignup from './mobileSignup';

export type StepIds = string; // or enum if you have it
export type SignupStep = { id: StepIds; title: string; isComplete: boolean };

export class SignupSteps {
  steps: SignupStep[] = [];
  currentStepId: StepIds | null = null;
  mobileSignup: MobileSignup | null = null;
  constructor() {
    makeAutoObservable(this);
  }

  init(steps: SignupStep[]) {
    this.steps = steps;
    this.currentStepId = steps[0]?.id ?? null;
  }

  setMobileSignup(mobileSignupInstance: MobileSignup) {
    this.mobileSignup = mobileSignupInstance;
  }

  get currentStepIndex() {
    const currentId = this.steps.findIndex((item) => !item.isComplete);
    return this.steps.findIndex((step) => step.id === this.steps[currentId]?.id);
  }

  get isLastStep() {
    const remainingSteps = this.steps
      .filter((s) => s.id !== 'aukapakkar')
      .filter((s) => !s.isComplete);
    return remainingSteps.length === 1;
  }

  get totalSteps() {
    return this.steps.length || 0;
  }

  findNextIncompleteStepIndex() {
    return this.steps.findIndex((s) => !s.isComplete);
  }

  get nextStepId() {
    if (this.mobileSignup?.isUpdatingSubscription) {
      return null;
    }
    const idx = this.findNextIncompleteStepIndex();
    return idx !== -1 ? this.steps[idx].id : null;
  }

  setCurrentStep(id: StepIds) {
    this.currentStepId = id;
  }

  resetStepsToKarfaStep() {
    const indexOfKarfa = this.steps.findIndex((i) => i.id === 'karfa');
    const newSteps = this.steps.map((item, v) => {
      if (v < indexOfKarfa) {
        item.isComplete = true;
      }
      return item;
    });

    this.steps = newSteps;
  }

  markStepComplete(id: StepIds) {
    const step = this.steps.find((s) => s.id === id);
    if (step) {
      step.isComplete = true;
    }
  }

  markStepIncomplete(id: StepIds) {
    const step = this.steps.find((s) => s.id === id);
    if (step) {
      step.isComplete = false;
    }
  }

  arePreviousStepsComplete(id: StepIds): boolean {
    const index = this.steps.findIndex((s) => s.id === id);
    if (index === -1) return false;
    return this.steps.slice(0, index).every((s) => s.isComplete);
  }

  getFirstIncompleteStepBefore(stepId: StepIds): SignupStep | null {
    const index = this.steps.findIndex((s) => s.id === stepId);
    if (index === -1) return null;

    return this.steps.slice(0, index).find((s) => !s.isComplete) ?? null;
  }
}

export const signupStepsStore = new SignupSteps();
