import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { IProductModel } from '@fleio-api/billing/model/product.model';
import { ISummaryCardData } from '@objects-view/interfaces/card-data/summary-card-data';
import { AuthService } from '@shared/auth/auth.service';
import { ConfigService } from '@shared/config/config.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss']
})
export class ProductListComponent implements OnInit {
  products: FleioObjectsList<IProductModel>;
  productDescriptionMaxLength = 170;

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private authService: AuthService,
    private config: ConfigService,
  ) {
  }

  ngOnInit(): void {
    this.products = this.activatedRoute.snapshot.data?.products;
  }

  orderProduct(product: IProductModel) {
    if (product.requires_domain && this.authService.feature('plugins.domains')) {
      if (this.config.authService.feature('ui.staff')) {
        this.router.navigateByUrl(this.config.getPanelUrl(`orders/select-domain/${product.code}`));
      } else {
        this.router.navigate(
          [`select-domain/${product.code}`], {relativeTo: this.activatedRoute}
        ).then(() => {
        });
      }
    } else {
      if (this.config.authService.feature('ui.staff')) {
        this.router.navigateByUrl(this.config.getPanelUrl(`orders/order-product/${product.code}`));
      } else {
        this.router.navigate(
          [`order-product/${product.code}`], {relativeTo: this.activatedRoute}
        ).then(() => {
        });
      }
    }
  }

  formatDescription(description) {
    if (description) {
      return description.length > this.productDescriptionMaxLength ?
        (description.slice(0, this.productDescriptionMaxLength) + '...') : description;
    }
    return null;
  }

  productCardData(product: IProductModel): ISummaryCardData {
    return {
      header: {
        title: {
          text: product.name,
        }
      },
      detailsLink: {
        enabled: false,
      },
      wrapContent: true,
      fields: [
        {
          value: this.formatDescription(product.description),
        }
      ],
      contentTooltip: (product.description && product.description.length > this.productDescriptionMaxLength) ?
        product.description : null,
      buttons: [
        {
          text: $localize`Order product`,
          click: () => {
            this.orderProduct(product);
          },
        }
      ]
    };
  }
}
