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 { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { ServiceUIService } from './service-ui.service';
import { IServiceModel } from '@fleio-api/billing/model/service.model';
import { IAction } from '@objects-view/interfaces/actions/action';
import { MatDialog } from '@angular/material/dialog';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { PluginsComponentsRegistryService } from '@shared/plugins/plugins-components-registry.service';

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

  constructor(
    private router: Router, private config: ConfigService, private servicesApiService: ServicesApiService,
    private matDialog: MatDialog, private pluginsComponentsRegistry: PluginsComponentsRegistryService,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new ServiceUIService(
      object as IServiceModel, permissions, state, this.router, this.config,
      this.servicesApiService, this.matDialog, this.pluginsComponentsRegistry,
    );
  }

  getTableData(objectList: FleioObjectsList<IServiceModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Value, displayName: $localize`Name`, enableSort: true, fieldName: 'name',
            flex: '300px', flexXs: '1 0 70px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Cycle`, enableSort: false, fieldName: 'cycle',
            flex: '110px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Created at`, enableSort: true, fieldName: 'created_at',
            flex: '100px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Paid until`, enableSort: true,
            fieldName: 'paid_until',
            flex: '150px', flexXs: '1 0 50px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Status`, enableSort: true, fieldName: 'status',
            flex: '100px', hide: {xs: true},
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: true, fieldName: '(actions)',
          },
        ],
        columnNames: ['name', 'cycle', 'created_at', 'paid_until', 'status', '(actions)'],
        showStatus: true,
      },
      rows: [],
    };

    for (const service of objectList.objects) {
      const rowUIService = this.getObjectUIService(service, objectList.permissions, 'table-view');

      let paidUntil = $localize`n/a`;
      let paidUntilTitle = $localize`n/a`;
      if (service.paid_until) {
        try {
          paidUntil = this.datePipe.transform(service.paid_until);
          paidUntilTitle = this.datePipe.getTitleAttributeValue(service.paid_until);
        } catch (e) {
        }
      }
      const row: ITableRow = {
        cells: {
          name: {
            text: service.display_name,
            subText: service.domain_name ? service.domain_name : null,
          },
          cycle: {text: !service.is_free ? service.cycle?.display_name : $localize`${service.cycle?.display_name} (free)`},
          created_at: {
            text: this.datePipe.transform(service.created_at),
            title: this.datePipe.getTitleAttributeValue(service.created_at)
          },
          paid_until: {
            text: paidUntil,
            title: paidUntilTitle,
          },
          status: {text: service.status.toLocaleUpperCase()},
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
        object: service,
      };

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