import { Injectable } from '@angular/core';
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 { ITableData } from '@objects-view/interfaces/table-data/table-data';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ITableRow } from '@objects-view/interfaces/table-data/table-row';
import { ColumnType } from '@objects-view/interfaces/table-data/column-definition';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { MatDialog } from '@angular/material/dialog';
import { ServiceCyclesApiService } from '@fleio-api/billing/service-cycles/service-cycles-api.service';
import { ServiceCycleUIService } from './service-cycle-ui.service';
import { IServiceCycleModel } from '@fleio-api/billing/service-cycles/models/service-cycle-model';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { ServiceCycleEditTrackerService } from './service-cycle-edit-tracker.service';
import { CurrencyFormatterPipe } from '@shared/ui/common/pipes/currency-formatter.pipe';

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

  constructor(
    private config: ConfigService,
    private serviceCyclesApiService: ServiceCyclesApiService,
    private matDialog: MatDialog,
    private refreshService: RefreshService,
    private serviceCycleEditTrackerService: ServiceCycleEditTrackerService,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
    this.currencyPipe = new CurrencyFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new ServiceCycleUIService(
      object as IServiceCycleModel, permissions, state, this.config, this.serviceCyclesApiService,
      this.matDialog, this.refreshService, this.serviceCycleEditTrackerService,
    );
  }

  getTableData(objectList: FleioObjectsList<IServiceCycleModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Value, displayName: $localize`ID`, enableSort: true, fieldName: 'id',
            flex: '50px', flexXs: '1 0 70px',
          },
          {
            type: ColumnType.Value, displayName: $localize`State`, enableSort: true, fieldName: 'state',
            flex: '90px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Start date`, enableSort: true, fieldName: 'start_dt',
            flex: '150px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`End date`, enableSort: true, fieldName: 'end_dt',
            flex: '150px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Price`, enableSort: true, fieldName: 'price',
            flex: '120px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Fixed price`, enableSort: true, fieldName: 'fixed_price',
            flex: '120px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Dynamic price`, enableSort: true, fieldName: 'dynamic_price',
            flex: '120px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Type`, enableSort: true, fieldName: 'type',
            flex: '100px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Billing type`, enableSort: true, fieldName: 'billing_type',
            flex: '100px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: true, fieldName: '(actions)'
          },
        ],
        columnNames: [
          'id', 'state', 'price', 'start_dt', 'end_dt', 'fixed_price', 'dynamic_price', 'type',
          'billing_type', '(actions)',
        ],
        showStatus: true,
      },
      rows: [],
    };

    for (const serviceCycle of objectList.objects) {
      const rowUIService = this.getObjectUIService(serviceCycle, objectList.permissions, 'table-view');
      let invoice = $localize`n/a`;
      let invoiceUrl = null;
      if (serviceCycle.invoice_id) {
        invoice = `#${serviceCycle.invoice_id}`;
        invoiceUrl = this.config.getPanelUrl('billing/invoices', serviceCycle.invoice_id);
      }
      const row: ITableRow = {
        cells: {
          id: {text: serviceCycle.id.toString()},
          state: {
            text: serviceCycle.state,
            subText: invoice,
            subTextLink: invoiceUrl,
          },
          start_dt: {
            text: this.datePipe.transform(serviceCycle.start_dt),
            title: serviceCycle.start_display,
          },
          end_dt: {
            text: this.datePipe.transform(serviceCycle.end_dt),
            title: serviceCycle.end_display,
          },
          price: {
            text: this.currencyPipe.transform(
              serviceCycle.standard_price, serviceCycle.currency, this.config.authService.currencyDisplayMode
            ),
            textStruck: serviceCycle.price_override,
            subText: serviceCycle.price_override ? this.currencyPipe.transform(
              serviceCycle.price, serviceCycle.currency, this.config.authService.currencyDisplayMode
            ) : null,
          },
          fixed_price: {
            text: this.currencyPipe.transform(
              serviceCycle.fixed_price, serviceCycle.currency, this.config.authService.currencyDisplayMode
            ),
          },
          dynamic_price: {
            text: this.currencyPipe.transform(
              serviceCycle.dynamic_price, serviceCycle.currency, this.config.authService.currencyDisplayMode
            ),
          },
          type: {text: serviceCycle.type},
          billing_type: {text: serviceCycle.billing_type},
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
        object: serviceCycle,
      };

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

    return tableData;
  }

  getActions(objectList: FleioObjectsList<IBaseFleioObjectModel>): IAction[] {
    return null;
  }

  getRefreshInterval(): number {
    return this.config.getDefaultRefreshInterval();
  }
}
