import { Component, OnInit, ViewChild } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IOrderModel } from '@fleio-api/billing/model/order.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ProductsApiService } from '@fleio-api/billing/products/product-api.service';
import { ConfigService } from '@shared/config/config.service';
import { IOrderOptionsModel } from '@fleio-api/billing/cart/model/order-options.model';
import { ActivatedRoute, Router } from '@angular/router';
import { NotificationService } from '@shared/ui-api/notification.service';
import { of } from 'rxjs';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { CartItemsApiService } from '@fleio-api/billing/cart/cart-items-api.service';

@Component({
  selector: 'app-add-new-order-form',
  templateUrl: './add-new-order-form.component.html',
  styleUrls: ['./add-new-order-form.component.scss']
})
export class AddNewOrderFormComponent extends DetailsFormBase<IOrderModel> implements OnInit {
  @ViewChild('pluginComponent') pluginComponent;

  orderForm = this.formBuilder.group({
    client: [null, Validators.required],
    currency: [null, Validators.required],
  });

  orderOptions: IOrderOptionsModel;
  backendErrors = {};
  availableCurrencies = [];

  preselectedClientId = null;
  currencyUnselectedPlaceholder = $localize`Select order currency ...`;
  currencySelectedPlaceholder = $localize`Order currency`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private cartItemsApi: CartItemsApiService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private notificationService: NotificationService,
    private clientsApiService: ClientsApiService,
    public productsApiService: ProductsApiService,
    public config: ConfigService,
  ) {
    super();
    this.preselectedClientId = activatedRoute.snapshot.params.client;
    if (this.preselectedClientId) {
      this.skipFirstFocusableInput = true;
    }
  }

  currenciesSwitchMap = (search) => {
    const lowerCaseValue = search.toLocaleLowerCase();
    return of(this.availableCurrencies.filter(
      currency => currency.toLocaleLowerCase().includes(lowerCaseValue)
    ));
  };

  ngOnInit(refreshTimerInterval?: number) {
    super.ngOnInit(refreshTimerInterval);

    if (this.objectController) {
      this.objectController.actionCallback = () => this.placeOrder();
    }

    this.orderForm.controls.client.valueChanges.subscribe(value => {
      if (value?.id) {
        this.clientsApiService.get(value.id).subscribe(client => {
          this.availableCurrencies = client.currencies;
          this.orderForm.controls.currency.setValue(client.currency);
        });
      }
    });

    if (this.preselectedClientId) {
      this.clientsApiService.get(this.preselectedClientId).subscribe(value => {
        this.orderForm.controls.client.setValue(value);
        this.orderForm.controls.currency.setValue(value.currency);
      });
    }
  }

  placeOrder() {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return of(null);
    }

    this.objectController.loading = true;
    this.cartItemsApi.startOrder(
      this.orderForm.controls.client.value.id,
      this.orderForm.controls.currency.value,
    ).subscribe({
      next: (response) => {
        this.router.navigateByUrl(
          this.config.getPanelUrl(`orders/select-product?filtering=cycles__currency__code:${response.cart_currency}`)
        ).then(() => {});
      }, error: (error) => {
        this.objectController.loading = false;
        if (error.status === 403) {
          this.notificationService.showMessage(
            error.error?.detail || $localize`You do not have permissions to order products`,
          );
        } else {
          this.backendErrors = error.error;
          this.formErrors.setBackendErrors(error.error);
        }
      }
    });
    return of(null);
  }

}
