import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  inject,
  Input,
  Output,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { ZoneService } from '@flaps/core';
import { IErrorMessages, PaButtonModule, PaIconModule, PaTogglesModule } from '@guillotinaweb/pastanaga-angular';
import { TranslateModule } from '@ngx-translate/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { StickyFooterComponent } from '@nuclia/sistema';
import { map } from 'rxjs';

const COWORK_ZONE_SLUGS = ['europe-1', 'aws-us-east-2-1'];

@Component({
  selector: 'nus-zone-step',
  imports: [
    CommonModule,
    PaButtonModule,
    PaIconModule,
    PaTogglesModule,
    ReactiveFormsModule,
    StickyFooterComponent,
    TranslateModule,
  ],
  templateUrl: './zone-step.component.html',
  styleUrls: ['../../_common-step.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ZoneStepComponent {
  private zoneService = inject(ZoneService);

  @Input() set data(value: string) {
    this.form.patchValue({ region: value });
  }

  @Input({ transform: booleanAttribute }) cowork = false;

  @Output() back = new EventEmitter<void>();
  @Output() next = new EventEmitter<string>();

  zones = this.zoneService.getZones().pipe(
    map((zones) => {
      if (this.cowork) {
        return zones
          .filter((z) => COWORK_ZONE_SLUGS.includes(z.slug ?? ''))
          .sort((a, b) => (a.title ?? '').localeCompare(b.title ?? ''));
      }
      return [...zones].sort((a, b) => (a.title ?? '').localeCompare(b.title ?? ''));
    }),
  );

  form = new FormGroup({
    region: new FormControl<string>('', { nonNullable: true, validators: [Validators.required] }),
  });

  validationMessages: IErrorMessages = {
    required: 'validation.required',
  };

  goBack() {
    this.back.emit();
  }

  submitForm() {
    this.next.emit(this.form.getRawValue().region);
  }
}
