import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { IConfigOptionModel } from '@fleio-api/billing/model/config-option.model';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { ConfigurableOptionsApiService } from '@fleio-api/billing/configurable-options/configurable-option-api.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
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 { CallbackAction } from '@objects-view/actions/callback-action';
import { IDataField } from '@objects-view/interfaces/card-data/data-field';
import { IDetailsTab } from '@objects-view/interfaces/details/details-tab';
import {
  ConfigurableOptionEditFormComponent
} from './tabs/configurable-option-edit-form/configurable-option-edit-form.component';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { IObjectStatus } from '@objects-view/interfaces/object-status';
import { ServicesApiService } from '@fleio-api/billing/services/service-api.service';
import { of } from 'rxjs';
import { NotificationService } from '@shared/ui-api/notification.service';
import {
  ConfigurableOptionDetailsOverviewComponent
} from './tabs/configurable-option-details-overview/configurable-option-details-overview.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';

export class ConfigurableOptionUiService extends ObjectUIServiceBase<IConfigOptionModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly configurableOptionsApiService: ConfigurableOptionsApiService;
  private readonly datePipe: DateFormatterPipe;

  constructor(
    configOption: IConfigOptionModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, configurableOptionsApiService: ConfigurableOptionsApiService,
    private servicesApi: ServicesApiService,
    private notificationService: NotificationService,
  ) {
    super(configOption, permissions, state);
    this.router = router;
    this.config = config;
    this.configurableOptionsApiService = configurableOptionsApiService;
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    return null;
  }

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

      case 'create':
        return {
          text: $localize`Create new configurable option`,
        };

      default:
        return {
          text: `${this.object.display_name}`,
        };
    }
  }

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

    actions.push(new RouterLinkAction({
        icon: {name: 'edit', class: 'fl-icons'},
        name: $localize`Edit`,
        tooltip: $localize`Edit configurable option`,
        noPermissions: !this.permissions['configurable-options.update'],
        routerUrl: this.config.getPanelUrl(`billing/configurable-options/${this.object.id}/edit`),
        router: this.router,
      }
    ))

    actions.push(new CallbackAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        tooltip: $localize`Delete configurable option`,
        name: $localize`Delete`,
        noPermissions: !this.permissions['configurable-options.destroy'],
        callback: () => {
          this.servicesApi.list({
            filtering: `configurable_options__option__id:${this.object.id}`
          }).subscribe(value => {
            if (value.count) {
              this.notificationService.confirmDialog(
                {
                  title: $localize`Cannot delete configurable option`,
                  message: $localize`Operation not permitted. One or more services are using this configurable option.`,
                  yesButtonName: $localize`Ok`,
                  hideNoButton: true,
                }
              );
            } else {
              const dialogResult$ = this.notificationService.confirmDialog({
                title: $localize`Delete configurable option`,
                message: $localize`Are you sure you want to delete configurable option ${this.object.name}?`,
                yesButtonName: $localize`Delete`,
              });
              dialogResult$.subscribe(dialogResult => {
                if (dialogResult?.button === 'yes') {
                  this.configurableOptionsApiService.delete(this.object.id).subscribe({
                    next: () => {
                      this.router.navigateByUrl(this.config.getPanelUrl('billing/configurable-options'));
                    },
                    error: (error) => {
                      if (error?.error?.detail) {
                        this.notificationService.showMessage(error.error.detail);
                      } else {
                        this.notificationService.showMessage(
                          $localize`Failed to delete configurable option, please check logs for details`
                        );
                      }
                    }
                  });
                }
              });
            }
          });
          return of(null);
        }
      }
    ));

    return actions;
  }

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`billing/configurable-options`),
            router: this.router,
          }
        ));
        actions.push(
          new CallbackAction({name: $localize`Create and continue`, internalName: 'Create and continue'})
        );
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Back`,
            routerUrl: this.config.getPrevUrl(`billing/configurable-options`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      default:
        break;
    }

    return actions;
  }

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

  getCardFields(): IDataField[] {
    const fields = [
      {name: $localize`Created at`, value: this.datePipe.toDateTime(this.object.created_at)},
    ];

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: ConfigurableOptionEditFormComponent,
          },
        ];
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: ConfigurableOptionDetailsOverviewComponent,
          },
          {
            tabName: $localize`Audit log`,
            tabIdentifier: 'audit-log',
            component: EntityAuditLogComponent,
            featureName: 'utils.activitylog',
            data: {
              entity_type: 'configurable_option'
            },
          }
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: ConfigurableOptionEditFormComponent,
          },
        ];
    }
  }

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