import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { ITitle } from '@objects-view/interfaces/card-data/card-title';
import { IObjectStatus, StatusType, StatusValue } from '@objects-view/interfaces/object-status';
import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { IAction } from '@objects-view/interfaces/actions/action';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { IDataField } from '@objects-view/interfaces/card-data/data-field';
import { IDetailsTab } from '@objects-view/interfaces/details/details-tab';
import { IServiceModel } from '@fleio-api/billing/model/service.model';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import {
  ServiceDetailsOverviewComponent
} from '@billing-service-tabs/service-details-overview/service-details-overview.component';
import { MatDialog } from '@angular/material/dialog';
import { ServiceChangeFormComponent } from '@billing-service-tabs/service-change-form/service-change-form.component';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { catchError, map } from 'rxjs/operators';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import {
  ServiceRequestCancellationComponent
} from './dialogs/service-request-cancellation/service-request-cancellation.component';
import { ApiCallAction } from '@objects-view/actions/api-call-action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { PluginsComponentsRegistryService } from '@shared/plugins/plugins-components-registry.service';
import { of } from 'rxjs';

export class ServiceUIService extends ObjectUIServiceBase<IServiceModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly servicesApiService: ServicesApiService;
  private readonly matDialog: MatDialog;


  constructor(
    service: IServiceModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, servicesApiService: ServicesApiService, matDialog: MatDialog,
    private pluginsComponentsRegistry: PluginsComponentsRegistryService,
  ) {
    super(service, permissions, state);
    this.matDialog = matDialog;
    this.router = router;
    this.config = config;
    this.servicesApiService = servicesApiService;
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    switch (this.object.status) {
      case 'active':
        return {type: StatusType.Defined, value: StatusValue.Active};
      case 'pending':
        return {type: StatusType.Defined, value: StatusValue.Pending};
      case 'suspended':
        return {type: StatusType.Defined, value: StatusValue.Suspended};
      case 'terminated':
        return {type: StatusType.Defined, value: StatusValue.Terminated};
      case 'canceled':
        return {type: StatusType.Defined, value: StatusValue.Canceled};
      case 'deleting':
        return {type: StatusType.Changing, value: StatusValue.Deleted};
      default:
        return {type: StatusType.None, value: StatusValue.None};
    }
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'edit':
        return {
          text: $localize`Edit ${this.object.display_name}`,
          subText: this.object.status.toLocaleUpperCase(),
        };

      case 'change-options':
        return {
          text: $localize`${this.object.display_name} - change service`,
        };
      case 'change-product':
        return {
          text: $localize`${this.object.display_name} - change product`,
        };
      default:
        let subText: string;
        if (this.object.domain_name) {
          subText = $localize`${this.object.domain_name}, ${this.object.status.toLocaleUpperCase()}`;
        } else {
          subText = this.object.status.toLocaleUpperCase();
        }
        return {
          text: `${this.object.display_name}`,
          subText,
        };
    }
  }

  getActions(): IAction[] {
    const actions: IAction[] = [];

    if (this.object.status !== 'terminated' && !this.object.cancellation_request) {
      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {
            class: 'fl-icons',
            name: 'delete',
          },
          tooltip: $localize`Cancel service`,
          name: $localize`Cancel service`,
          callback: () => this.matDialog.open(
            ServiceRequestCancellationComponent, {
              data: {service: this.object},
              autoFocus: false,
            }).afterClosed().pipe(map(result => {
            if (result === false || typeof result === 'undefined') {
              return;
            }
            return {message: result} as IActionResult;
          }))
        }
      ));
    }

    if (
      this.config.authService.feature('ui.billing.services.upgrade-downgrade') &&
      ['pending', 'active'].includes(this.object.status) && !this.object.resources.disabled_features.includes('upgrade')
    ) {
      actions.push(new RouterLinkAction({
          name: $localize`Upgrade`,
          icon: {name: 'upgrade'},
          tooltip: $localize`Upgrade`,
          routerUrl: this.config.getPanelUrl(`billing/services/${this.object.id}/change`),
          router: this.router,
        }
      ));
    }

    for (const action of Object.keys(this.object.actions)) {
      const actionDefinition = this.object.actions[action];
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: actionDefinition.icon},
          tooltip: actionDefinition.description,
          name: actionDefinition.display_name,
          confirmOptions: {
            confirm: true,
            title: actionDefinition.description,
            message: $localize`Are you sure you want to ${actionDefinition.display_name.toLocaleLowerCase()} service ${this.object.display_name}?`,
          },
          apiService: this.servicesApiService,
          apiAction: 'execute_action',
          apiParams: {
            action
          },
          refreshAfterExecute: true,
        }
      ));
    }

    if (this.object.resources.can_renew_early) {
      actions.push(new CallbackAction({
        icon: {name: 'receipt'},
        tooltip: $localize`Renew early`,
        name: $localize`Renew early`,
        displayMessages: true,
        confirmOptions: {
          confirm: true,
          title: $localize`Renew early`,
          message: $localize`Renew ${this.object.display_name} early?`,
        },
        refreshAfterExecute: true,
        callback: () => this.servicesApiService.renewEarly(this.object.id).pipe(map((result) => {
          if (result?.invoice_id) {
            this.router.navigateByUrl(
              this.config.getPanelUrl(`billing/invoices/${result.invoice_id}`),
            ).then(() => {
            });
          }
          return {
            success: true,
            message: result.detail,
          } as IActionResult;
        }), catchError((error) => {
          return of({success: false, message: error.error.detail} as IActionResult)
        }))
      }),)
    }

    return actions;
  }

  getDetailsLink(): string {
    return this.config.getPanelUrl(`billing/services/${this.object.id}`);
  }

  getCardFields(): IDataField[] {
    const datePipe = new DateFormatterPipe(this.config);
    let paid_until = $localize`n/a`;
    let paid_until_title = $localize`n/a`;
    if (this.object.paid_until) {
      try {
        paid_until = datePipe.transform(this.object.paid_until)
        paid_until_title = datePipe.getTitleAttributeValue(this.object.paid_until)
      } catch (e) {
      }
    }

    return [
      {
        name: $localize`Created at`,
        value: `${datePipe.transform(this.object.created_at)}`,
        title: `${datePipe.getTitleAttributeValue(this.object.created_at)}`,
      },
      {
        name: $localize`Paid until`,
        value: paid_until,
        title: paid_until_title,
      }
    ];
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        const tabs: IDetailsTab[] = [];

        const pluginTabs = this.pluginsComponentsRegistry.getServiceTabs(
          this.object.resources.plugin_name, 'enduser',
        )

        let newOverviewTab = false;
        for (const pluginTabName of Object.keys(pluginTabs)) {
          if (pluginTabName.toLowerCase() === 'overview') {
            newOverviewTab = true;
          }
          tabs.push({
            tabName: pluginTabs[pluginTabName].tabDisplayName,
            tabIdentifier: pluginTabName,
            component: pluginTabs[pluginTabName].component,
            data: {
              isPluginTab: true,
            }
          });
        }

        tabs.push(
          {
            tabName: newOverviewTab ? $localize`Service details` : $localize`Overview`,
            tabIdentifier: newOverviewTab ? 'service details' : 'overview',
            component: ServiceDetailsOverviewComponent,
          })

        return tabs;
      case 'change':
        return [
          {
            tabName: $localize`Change`,
            tabIdentifier: 'change',
            component: ServiceChangeFormComponent,
          },
        ];
    }
  }

  getCardTags(): string[] {
    const tags = [];

    if (this.object.cancellation_request) {
      tags.push($localize`Cancellation requested`);
    }

    return tags;
  }

  getDetailsActions(): IAction[] {
    if (this.object.resources.can_renew_early) {
      return [
        new CallbackAction({
          icon: {name: 'receipt'},
          tooltip: $localize`Renew early`,
          name: $localize`Renew early`,
          displayMessages: true,
          confirmOptions: {
            confirm: true,
            title: $localize`Renew early`,
            message: $localize`Renew ${this.object.display_name} early?`,
          },
          refreshAfterExecute: true,
          callback: () => this.servicesApiService.renewEarly(this.object.id).pipe(map((result) => {
            if (result?.invoice_id) {
              this.router.navigateByUrl(
                this.config.getPanelUrl(`billing/invoices/${result.invoice_id}`),
              ).then(() => {
              });
            }
            return {
              success: true,
              message: result.detail,
            } as IActionResult;
          }), catchError((error) => {
            return of({success: false, message: error.error.detail} as IActionResult)
          }))
        }),
      ]
    }

    return [];
  }
}
