import { Component, ChangeDetectionStrategy, inject, OnInit } from '@angular/core';
import { UiModalRef } from '@ui/modal';
import { SendOrderConfirmationModalData, SendOrderConfirmationModalResult } from './types';
import { FormControldModule } from '@shared/components/form-control';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { IconComponent } from '@shared/components/icon';
import { NotificationChannel, OrderService } from '@generated/swagger/oms-api';
import { ToasterService } from '@shared/shell';
import { validateEmail } from 'apps/isa-app/src/page/customer/validators/email-validator';

@Component({
  selector: 'shared-send-order-confirmation-modal',
  templateUrl: 'send-order-confirmation-modal.component.html',
  styleUrls: ['send-order-confirmation-modal.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'shared-send-order-confirmation-modal' },
  imports: [FormControldModule, ReactiveFormsModule, IconComponent],
})
export class SendOrderConfirmationModalComponent implements OnInit {
  toaster = inject(ToasterService);

  orderService = inject(OrderService);

  emailControl = new FormControl('', [Validators.required, Validators.email, validateEmail]);

  readonly modalRef: UiModalRef<SendOrderConfirmationModalResult, SendOrderConfirmationModalData> = inject(UiModalRef);

  ngOnInit(): void {
    const email = this.modalRef.data.map((order) => order.buyer?.communicationDetails?.email).find((email) => !!email);

    if (email) {
      this.emailControl.setValue(email);
    }
  }

  async sendOrderConfirmation() {
    if (this.emailControl.invalid || this.emailControl.disabled) {
      this.emailControl.markAllAsTouched();
      return;
    }

    this.emailControl.disable();

    const email = this.emailControl.value;

    for (let order of this.modalRef.data) {
      let notificationChannels = order.notificationChannels ?? 0;
      notificationChannels = (1 | notificationChannels) as NotificationChannel;

      try {
        await this.orderService
          .OrderPatchOrder({
            orderId: order.id,
            order: { notificationChannels, buyer: { communicationDetails: { email } } },
          })
          .toPromise();
        const response = await this.orderService.OrderOrderConfirmationTask(order.id).toPromise();
        this.toaster.open({
          type: 'success',
          message: `Bestellbestätigung für die Bestellung ${order.orderNumber} wurde erfolgreich versendet`,
        });
        this.modalRef.close(response.result);
        return;
      } catch (error) {
        this.toaster.open({
          type: 'danger',
          message: `Fehler beim Versenden der Bestellbestätigung für die Bestellung ${order.orderNumber}`,
        });
      }

      this.emailControl.enable();
    }
  }
}
