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 { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { MatDialog } from '@angular/material/dialog';
import { ServiceCycleEditTrackerService } from '../service-cycles/service-cycle-edit-tracker.service';
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 serviceCycleEditTrackerService: ServiceCycleEditTrackerService,
    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.serviceCycleEditTrackerService, this.pluginsComponentsRegistry,
    );
  }

  getTableData(objectList: FleioObjectsList<IServiceModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Value, displayName: $localize`Name`, enableSort: true, fieldName: 'name',
            flex: '250px', flexXs: '1 0 70px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Client`, enableSort: true, fieldName: 'client',
            flex: '150px', hide: {xs: true, sm: true},
          },
          {
            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, md: 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', 'client', 'cycle', 'created_at', 'paid_until', 'status', '(actions)'],
        showStatus: true,
        visibleActions: 2,
      },
      rows: [],
    };

    for (const service of objectList.objects) {
      const rowUIService = this.getObjectUIService(service, objectList.permissions, 'table-view');
      let paid_until = $localize`n/a`;
      let paid_until_title = $localize`n/a`;
      if (service.paid_until) {
        try {
          paid_until = this.datePipe.transform(service.paid_until);
          paid_until_title = 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,
          },
          client: {
            text: service.client.display,
            url: this.config.getPanelUrl(`clients-users/clients/${service.client.id}`)
          },
          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: paid_until,
            title: paid_until_title,
          },
          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();
  }
}
