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

export interface ICreateConsumerStepperResult {
  consumer: IPartnerConsumerResponse;
  businessActivity: IBusinessActivityResponse;
  complex: IComplexResponse;
  pos: IPosResponse;
}

@Component({
  selector: 'partner-create-consumer-wrapper',
  templateUrl: './create-consumer-wrapper.component.html',
  imports: [
    Stepper,
    StepList,
    Step,
    ConsumerUserFormContentComponent,
    ConsumerBusinessActivitiesFormComponent,
    ConsumerComplexFormContentComponent,
    ConsumerPosFormContentComponent,
    SharedDialogComponent,
  ],
})
export class CreateConsumerWrapperComponent extends AbstractDialog {
  @Output() onSubmit = new EventEmitter<ICreateConsumerStepperResult>();

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

  constructor() {
    super();

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

  onConsumerSubmit(response: IPartnerConsumerResponse) {
    this.consumer.set(response);
    this.activeStep.set(2);
  }

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

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

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

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

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

    this.close();
  }

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

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