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 { RouterLinkAction } from '@objects-view/actions/router-link-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 { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { IMessageTemplateModel } from '@fleio-api/message-templates/model/message-template.model';
import { MessageTemplatesApiService } from '@fleio-api/message-templates/message-templates-api.service';
import { MessageTemplateEditFormComponent } from './tabs/message-template-edit-form/message-template-edit-form.component';
import {
  MessageTemplateCreateFormComponent
} from './tabs/message-template-create-form/message-template-create-form.component';
import { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';


export class MessageTemplateUIService extends ObjectUIServiceBase<IMessageTemplateModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly messageTemplatesApiService: MessageTemplatesApiService;
  private readonly datePipe: DateFormatterPipe;


  constructor(
    messageTemplate: IMessageTemplateModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, messageTemplatesApiService: MessageTemplatesApiService
  ) {
    super(messageTemplate, permissions, state);
    this.router = router;
    this.config = config;
    this.messageTemplatesApiService = messageTemplatesApiService;
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    let object;
    if (Array.isArray(this.object)) {
      // on edit, we actually have list of records that represent the same template (have the same name)
      object = this.object[0];
    } else {
      object = this.object;
    }
    switch (object.disable_notification) {
      case true:
        return {type: StatusType.Defined, value: StatusValue.Disabled};
      case false:
        return {type: StatusType.Defined, value: StatusValue.Active};
      default:
        return {type: StatusType.Defined, value: StatusValue.Disabled};
    }
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'edit':
        return {
          text: $localize`Edit ${this.object[0].name}`,
          subText: $localize`Category: ${this.object[0].category_display}`,
        };
      case 'create':
        return {
          text: $localize`Create new message template`,
        };
      default:
        return {
          text: `${this.object.name}`,
          subText: $localize`Category: ${this.object.category_display}`,
        };
    }
  }

  additionalActionStates(): Array<string> {
    return ['edit'];
  }

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

    if (this.state !== 'edit') {
      actions.push(new RouterLinkAction({
          icon: {name: 'edit', class: 'fl-icons'},
          name: $localize`Edit`,
          tooltip: $localize`Edit message template`,
          routerUrl: this.config.getPanelUrl(`settings/message-templates/${this.object.id}/edit`),
          router: this.router,
          noPermissions: !this.permissions['messagetemplates.update']
        }
      ));
    }

    let templateType;
    let refreshAfterExecute;
    let redirectAfterExecute;
    let object;
    if (this.state === 'edit') {
      refreshAfterExecute = false;
      redirectAfterExecute = true;
      templateType = this.object[0].type;
      object = this.object[0];
    } else {
      refreshAfterExecute = true;
      redirectAfterExecute = false;
      templateType = this.object.type;
      object = this.object;
    }
    if (templateType === 'custom') {
      actions.push(new ApiCallAction(
        {
          object,
          icon: {name: 'delete'},
          tooltip: $localize`Delete`,
          name: $localize`Delete`,
          confirmOptions: {
            confirm: true,
            title: $localize`Delete`,
            message: $localize`Are you sure you want to delete template ${this.object.name}?`,
            importantMessage: $localize`Templates of all languages of this kind will be deleted.`,
          },
          successMessage: $localize`message template deleted`,
          apiService: this.messageTemplatesApiService,
          callType: CallType.Delete,
          redirectAfterExecute,
          redirectUrl: this.config.getPanelUrl('settings/message-templates'),
          refreshAfterExecute,
        }
      ));
    }

    return actions;
  }

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`settings/message-templates`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Create`}));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`settings/message-templates`),
            router: this.router,
          }
        ));
        if (!this.object[0].has_all_available_languages) {
          actions.push(new CallbackAction({name: $localize`Add new template`, internalName: 'add', primary: false}));
        }
        actions.push(new CallbackAction({name: $localize`Save templates`, internalName: 'save', primary: true}));
        break;
      default:
        actions.push(new RouterLinkAction({
            name: $localize`Back`,
            routerUrl: this.config.getPrevUrl(`settings/message-templates`),
            router: this.router,
          }
        ));
        break;
    }

    return actions;
  }

  getDetailsLink(): string {
    return this.config.getPanelUrl(`settings/message-templates/${this.object.id}/edit`);
  }

  getCardFields(): IDataField[] {
    const fields = [];

    fields.push({
      name: 'Title',
      value: this.object.title,
    });

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        return [];
      case 'create':
        return [
          {
            tabName: $localize`Create message template`,
            tabIdentifier: 'create-message-template',
            component: MessageTemplateCreateFormComponent,
          },
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: MessageTemplateEditFormComponent,
          },
        ];
    }
  }

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

    tags.push(this.object.language);

    return tags;
  }
}
