import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { IObjectStatus, StatusType, StatusValue } from '@objects-view/interfaces/object-status';
import { ITitle } from '@objects-view/interfaces/card-data/card-title';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { IDataField } from '@objects-view/interfaces/card-data/data-field';
import { IDetailsTab } from '@objects-view/interfaces/details/details-tab';
import { IDomainModel } from '@fleio-api/plugins/domains/model/domain.model';
import { DomainApiService } from '@fleio-api/plugins/domains/domain-api.service';
import {
  DomainTransferFormComponent
} from '@shared/plugins/common-tabs/domains/domain-transfer-form/domain-transfer-form.component';
import {
  DomainRegisterFormComponent
} from '@shared/plugins/common-tabs/domains/domain-register-form/domain-register-form.component';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { catchError, map } from 'rxjs/operators';
import { of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';


export class DomainUiService extends ObjectUIServiceBase<IDomainModel> {
  private readonly datePipe: DateFormatterPipe;


  constructor(
    domain: IDomainModel, permissions: IPermissionsModel, state: string,
    private router: Router,
    private config: ConfigService,
    private domainApiService: DomainApiService,
    private servicesApiService: ServicesApiService,
  ) {
    super(domain, permissions, state);
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    switch (this.object.status) {

      case 'undefined':
      case 'unmanaged':
        return {type: StatusType.Defined, value: StatusValue.Disabled};

      case 'pending':
      case 'pending_transfer':
        return {type: StatusType.Defined, value: StatusValue.Pending};
      case 'active':
      case 'grace':
      case 'redemption':
        return {type: StatusType.Defined, value: StatusValue.Active};
      case 'deleted':
        return {type: StatusType.Defined, value: StatusValue.Deleted};
      case 'expired':
      case 'canceled':
      case 'fraud':
        return {type: StatusType.Defined, value: StatusValue.Canceled};

      case 'transferred_away':
        return {type: StatusType.Defined, value: StatusValue.Deactivated};
    }
    return null;
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'details':
        return {
          text: `${this.object.name}`,
          subText: `${this.object.status_display}`,
        };

      case 'transfer':
        return {
          text: $localize`Transfer domain`,
        };

      case 'register':
        return {
          text: $localize`Register domain`,
        };

      default:
        return {
          text: `${this.object.name}`,
          subText: `${this.object.status_display}`,
        };
    }
  }

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

    if (this.object.status === 'active') {
      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 early domain ${this.object.name}?`,
        },
        refreshAfterExecute: true,
        callback: () => this.servicesApiService.renewEarly(this.object.service).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;
  }

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

    switch (this.state) {
      case 'details':
        actions.push(new RouterLinkAction({
            name: $localize`Back`,
            routerUrl: this.config.getPrevUrl(`domains`),
            router: this.router,
          }
        ));
        break;
      default:
        break;
    }

    return actions;
  }

  getDetailsLink(): string {
    return this.config.getPanelUrl(`domains/${this.object.service}`);
  }

  getCardFields(): IDataField[] {
    return [
      {name: $localize`Created at`, value: this.datePipe.toDateTime(this.object.created_at)},
      {
        name: $localize`Registrar`,
        value: this.object.last_registrar_name ? this.object.last_registrar_name : $localize`n/a`
      },
    ];
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'transfer':
        return [
          {
            tabName: $localize`Transfer`,
            tabIdentifier: 'transfer',
            component: DomainTransferFormComponent,
          },
        ];
      case 'register':
        return [
          {
            tabName: $localize`Register`,
            tabIdentifier: 'register',
            component: DomainRegisterFormComponent,
          },
        ];
    }
  }

  getCardTags(): string[] {
    return [];
  }
}
