import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IObjectListUIService } from '@objects-view/interfaces/object-list-ui-service';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { ConfigService } from '@shared/config/config.service';
import { IObjectUIService } from '@objects-view/interfaces/object-ui-service';
import { IInvoiceModel } from '@fleio-api/billing/model/invoice.model';
import { InvoiceUIService } from './invoice-ui.service';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ITableData } from '@objects-view/interfaces/table-data/table-data';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { InvoicesApiService } from '@fleio-api/billing/invoices/invoices-api.service';
import { ColumnType } from '@objects-view/interfaces/table-data/column-definition';
import { ITableRow } from '@objects-view/interfaces/table-data/table-row';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { MatDialog } from '@angular/material/dialog';
import { CurrencyFormatterPipe } from '@shared/ui/common/pipes/currency-formatter.pipe';

@Injectable({
  providedIn: 'root',
})
export class InvoiceListUIService implements IObjectListUIService {
  public noItemsMessage = $localize`No invoices`;
  private datePipe: DateFormatterPipe;
  private currencyPipe: CurrencyFormatterPipe;

  constructor(private router: Router, private config: ConfigService, private invoicesApi: InvoicesApiService,
              private matDialog: MatDialog,) {
    this.datePipe = new DateFormatterPipe(this.config);
    this.currencyPipe = new CurrencyFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new InvoiceUIService(
      object as IInvoiceModel, permissions, state, this.router, this.config, this.invoicesApi, this.matDialog,
    );
  }

  getTableData(objectList: FleioObjectsList<IInvoiceModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {type: ColumnType.Value, displayName: $localize`ID`, enableSort: true, fieldName: 'display_number'},
          {
            type: ColumnType.Value, displayName: $localize`Status`, enableSort: true, fieldName: 'status',
            hide: {xs: true},
          },
          {type: ColumnType.Value, displayName: $localize`Issue date`, enableSort: true, fieldName: 'issue_date'},
          {type: ColumnType.Currency, displayName: $localize`Total`, enableSort: true, fieldName: 'total'},
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
            flex: '100px', flexXs: '50px'
          },
        ],
        columnNames: ['display_number', 'status', 'issue_date', 'total', '(actions)'],
        showStatus: true,
        visibleActions: 1,
      },
      rows: [],
    };

    for (const invoice of objectList.objects) {
      const rowUIService = this.getObjectUIService(invoice, objectList.permissions, 'table-view');
      const row: ITableRow = {
        cells: {
          display_number: {text: invoice.display_number},
          status: {text: invoice.status.toLocaleUpperCase()},
          issue_date: {
            text: this.datePipe.transform(invoice.issue_date),
            title: this.datePipe.getTitleAttributeValue(invoice.issue_date),
          },
          total: {
            text: this.currencyPipe.transform(
              invoice.total, invoice.currency, this.config.authService.currencyDisplayMode, null
            )
          },
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
        object: invoice,
      };

      tableData.trackByFunction = (index, item: ITableRow) => item.object.id;
      tableData.rows.push(row);
    }

    return tableData;
  }

  getActions(objectList: FleioObjectsList<IBaseFleioObjectModel>): IAction[] {
    return [
      new RouterLinkAction({
        icon: {name: 'add'},
        name: $localize`Create`,
        tooltip: $localize`Create new invoice`,
        routerUrl: this.config.getPanelUrl(`billing/invoices/create`),
        router: this.router,
      }),
    ];
  }

  getRefreshInterval(): number {
    if (this.config && this.config.current && this.config.current.settings &&
      this.config.current.settings.refreshIntervals) {
      return this.config.current.settings.refreshIntervals.defaultInterval;
    }
    return 10000;
  }
}
