import { AbstractDialog } from '@/shared/abstractClasses/abstract-dialog';
import { SharedDialogComponent } from '@/shared/components/dialog/dialog.component';
import { Component, effect, EventEmitter, Input, Output, signal } from '@angular/core';
import { Step, StepList, Stepper } from 'primeng/stepper';
import { IBusinessActivityResponse, IComplexResponse, IPosResponse } from '../../../models';
import { ConsumerComplexFormContentComponent } from '../../complexes/form.component';
import { ConsumerPosFormContentComponent } from '../../poses/form.component';
import { ConsumerBusinessActivitiesFormComponent } from '../form.component';

export interface ICreateBusinessActivityStepperResult {
  businessActivity: IBusinessActivityResponse;
  complex: IComplexResponse;
  pos: IPosResponse;
}

@Component({
  selector: 'partner-consumer-businessActivities-create-wrapper',
  templateUrl: './create-wrapper.component.html',
  imports: [
    SharedDialogComponent,
    Stepper,
    StepList,
    Step,
    ConsumerBusinessActivitiesFormComponent,
    ConsumerComplexFormContentComponent,
    ConsumerPosFormContentComponent,
  ],
})
export class ConsumerBusinessActivitiesCreateWrapperComponent extends AbstractDialog {
  @Input({ required: true }) consumerId!: string;
  @Output() onSubmit = new EventEmitter<ICreateBusinessActivityStepperResult>();

  activeStep = signal(1);
  businessActivity = signal<IBusinessActivityResponse | null>(null);
  complex = signal<IComplexResponse | null>(null);

  constructor() {
    super();

    effect(() => {
      if (this.visible) {
        this.resetWizard();
      }
    });
  }

  onBusinessActivitySubmit(response: IBusinessActivityResponse) {
    this.businessActivity.set(response);
    this.activeStep.set(2);
  }

  onComplexSubmit(response: IComplexResponse) {
    this.complex.set(response);
    this.activeStep.set(3);
  }

  onPosSubmit(response: IPosResponse) {
    const businessActivity = this.businessActivity();
    const complex = this.complex();

    if (!businessActivity || !complex) {
      return;
    }

    this.onSubmit.emit({
      businessActivity,
      complex,
      pos: response,
    });

    this.close();
  }

  override close() {
    this.resetWizard();
    super.close();
  }

  private resetWizard() {
    this.activeStep.set(1);
    this.businessActivity.set(null);
    this.complex.set(null);
  }
}
