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 { 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 { MatDialog } from '@angular/material/dialog';
import { CommonJournalUiService } from '@common-object-ui/billing/journal/common-journal-ui.service';
import { IJournalEntryModel } from '@fleio-api/billing/model/journal-entry.model';
import { JournalsApiService } from '@fleio-api/billing/journal/journal-api.service';
import { AppColor } from '@shared/ui/common/enums/app-color.enum';
import { ITableCell } from '@objects-view/interfaces/table-data/table-cell';
import { NotificationService } from '@shared/ui-api/notification.service';
import { GatewayApiService } from '@fleio-api/billing/gateways/gateway-api.service';
import { JournalEditTrackerService } from '../../../../../staff/billing/journal/journal-edit-tracker.service';
import { CurrencyFormatterPipe } from '@shared/ui/common/pipes/currency-formatter.pipe';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';

@Injectable({
  providedIn: 'root',
})
export class CommonJournalListUiService implements IObjectListUIService {
  public noItemsMessage = $localize`No journal entries`;
  protected datePipe: DateFormatterPipe;
  protected currencyPipe: CurrencyFormatterPipe;

  constructor(
    protected router: Router,
    protected config: ConfigService,
    protected journalsApiService: JournalsApiService,
    protected matDialog: MatDialog,
    protected gatewayApiService: GatewayApiService,
    protected notificationService: NotificationService,
    protected journalEditTrackerService: JournalEditTrackerService,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
    this.currencyPipe = new CurrencyFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new CommonJournalUiService(
      object as IJournalEntryModel, permissions, state, this.router, this.config, this.journalsApiService,
      this.matDialog, this.gatewayApiService, this.notificationService
    );
  }

  getTableDataDict(): ITableData {
    return {
      header: {
        columns: [
          {
            type: ColumnType.Value, displayName: $localize`Date`, enableSort: true, fieldName: 'date_added',
            flex: '180px', flexXs: '105px'
          },
          {
            type: ColumnType.Value, displayName: $localize`Source info`, enableSort: true, fieldName: 'source',
            flex: '350px', hide: {xs: true, md: true, sm: true}
          },
          {
            type: ColumnType.Value, displayName: $localize`Destination info`, enableSort: true, fieldName: 'destination',
            flex: '250px', flexXs: '1 0 50px'
          },
          {
            type: ColumnType.Currency, displayName: $localize`Amount`, enableSort: true, fieldName: 'destination_amount',
          },
          {
            type: ColumnType.Actions, displayName: '', enableSort: false, fieldName: '(actions)',
            hide: {xs: true}
          },
        ],
        columnNames: ['date_added', 'source', 'destination', 'destination_amount', '(actions)'],
        showStatus: false,
      },
      rows: [],
      alwaysShowActions: true,
    };
  }

  getCells(journalEntry, sourceInfoSubText, sourceInfoSubTextLink, destinationInfoSubText, destinationInfoSubTextLink,
           destinationAmount) {
    return {
      date_added: {
        text: `${this.datePipe.transform(journalEntry.date_added)}`,
        title: `${this.datePipe.getTitleAttributeValue(journalEntry.date_added)}`,
      },
      source: {text: journalEntry.source_info.name, subText: sourceInfoSubText, subTextLink: sourceInfoSubTextLink},
      destination: {text: journalEntry.destination_info.name, subText: destinationInfoSubText,
        subTextLink: destinationInfoSubTextLink},
      destination_amount: destinationAmount
    };
  }

  getTableData(objectList: FleioObjectsList<IJournalEntryModel>): ITableData {
    const tableData: ITableData = this.getTableDataDict();

    for (const journalEntry of objectList.objects) {
      const rowUIService = this.getObjectUIService(journalEntry, objectList.permissions, 'table-view');
      let sourceInfoSubText;
      let sourceInfoSubTextLink;
      if (journalEntry.source_info.invoice) {
        sourceInfoSubText = $localize`Invoice ${journalEntry.source_info.invoice}`;
        sourceInfoSubTextLink = this.config.getPanelUrl(`billing/invoices/${journalEntry.source_info.invoice}`);
      }
      if (journalEntry.source_info.transaction) {
        sourceInfoSubText = $localize`Transaction ${journalEntry.source_info.transaction}`;
      }
      if (!sourceInfoSubText && journalEntry.source === 'cr' &&
        ['iv', 'st', 'ex'].indexOf(journalEntry.destination) > -1) {
        sourceInfoSubText = $localize`Client credit`;
      }
      let destinationInfoSubText;
      let destinationInfoSubTextLink;
      if (journalEntry.destination_info.invoice) {
        destinationInfoSubText = $localize`Invoice ${journalEntry.destination_info.invoice}`;
        destinationInfoSubTextLink = this.config.getPanelUrl(`billing/invoices/${journalEntry.destination_info.invoice}`);
      }
      if (journalEntry.destination_info.transaction) {
        destinationInfoSubText = $localize`Transaction ${journalEntry.destination_info.transaction}`;
      }
      if (!destinationInfoSubText && ['iv', 'st', 'ex'].indexOf(journalEntry.source) > -1 &&
        journalEntry.destination === 'cr') {
        destinationInfoSubText = $localize`Client credit`;
      }
      const destinationAmount = {
        text: this.currencyPipe.transform(
          journalEntry.destination_amount, journalEntry.destination_currency, this.config.authService.currencyDisplayMode
        )
      } as ITableCell;
      if (journalEntry.direction === 'outgoing') {
        destinationAmount.text = '- ' + destinationAmount.text;
        destinationAmount.textColor = AppColor.Red;
      } else if (journalEntry.direction === 'incoming') {
        destinationAmount.textColor = AppColor.Green;
      }
      if (journalEntry.needs_capture) {
        destinationAmount.textColor = AppColor.Orange;
      }
      const row: ITableRow = {
        cells: this.getCells(
          journalEntry, sourceInfoSubText, sourceInfoSubTextLink, destinationInfoSubText, destinationInfoSubTextLink,
          destinationAmount,
        ),
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
        object: journalEntry,
      };

      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();
  }
}
