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 { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';
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 { IUserModel } from '@fleio-api/client-user/model/user.model';
import { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
import { AuthService } from '@shared/auth/auth.service';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';
import { UserDetailsOverviewComponent } from './tabs/user-details-overview/user-details-overview.component';
import { UserDetailsClientsComponent } from './tabs/user-details-clients/user-details-clients.component';
import { UserDetailsGroupsComponent } from './tabs/user-details-groups/user-details-groups.component';
import { UserDetailsTicketsComponent } from './tabs/user-details-tickets/user-details-tickets.component';
import { UserDetailsLogComponent } from './tabs/user-details-log/user-details-log.component';
import { UserEditFormComponent } from './tabs/user-edit-form/user-edit-form.component';
import { UserDetailsPermissionsComponent } from './tabs/user-details-permissions/user-details-permissions.component';

export class UserUIService extends ObjectUIServiceBase<IUserModel> {
  constructor(
    user: IUserModel, permissions: IPermissionsModel, state: string,
    private readonly router: Router,
    private readonly config: ConfigService,
    private readonly usersApi: UsersApiService,
    private auth: AuthService,
  ) {
    super(user, permissions, state);
    this.auth = auth;
    this.router = router;
    this.config = config;
    this.usersApi = usersApi;
  }

  getIcon(): IIcon {
    if (this.object && this.object.email) {
      return {
        name: '(gravatar)',
        gravatarEmail: this.object.email,
      };
    }
    return null;
  }

  getStatus(): IObjectStatus {
    if (this.state === 'create') {
      return {type: StatusType.None, value: StatusValue.None};
    }
    return {
      type: StatusType.Defined,
      value: this.object.is_active ? StatusValue.Active : StatusValue.Error
    };
  }

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

      case 'edit':
        return {
          text: `${this.object.first_name} ${this.object.last_name}`,
          subText: this.object.email,
        };

      case 'create':
        return {
          text: $localize`Create user`,
        };

      default:
        return {
          text: `${this.object.first_name} ${this.object.last_name}`,
          subText: this.object.email,
        };
    }
  }

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

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

    if (!this.object.is_superuser && !this.object.is_staff && this.object.is_active) {
      actions.push(new RouterLinkAction({
          icon: {name: 'face'},
          name: $localize`Impersonate user`,
          noPermissions: !this.permissions['users.impersonate'],
          disabled: this.auth.isImpersonating(),
          tooltip: this.auth.isImpersonating() ?
            $localize`You cannot impersonate another user while impersonating` : $localize`Impersonate user`,
          routerUrl: this.config.getPanelUrl(`clients-users/users/${this.object.id}/impersonate`),
          router: this.router,
        }
      ));
    }

    if (this.object.sfa_enabled && (!(this.object.is_staff || this.object.is_superuser) || this.auth.isSuperUser())) {
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: 'lock_open'},
          name: 'Disable SFA',
          tooltip: 'Disable second factor authentication',
          featureName: 'clients&users.second_factor_auth',
          confirmOptions: {
            confirm: true,
            title: $localize`Disable second factor authentication`,
            message: $localize`Are you sure you want to disable second factor authentication for user ${this.object.display}?`,
          },
          successMessage: $localize`Second factor authentication disabled`,
          errorMessage: $localize`Failed to disable second factor authentication, check logs for details`,
          apiService: this.usersApi,
          callType: CallType.Post,
          apiAction: 'disable-sfa',
          refreshAfterExecute: true,
        }
      ));
    }


    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        name: 'Delete',
        tooltip: 'Delete',
        noPermissions: !this.permissions['users.destroy'],
        confirmOptions: {
          confirm: true,
          title: $localize`Delete user`,
          message: $localize`Are you sure you want to delete user ${this.object.display}?. All data will be lost.`,
        },
        successMessage: $localize`User deleted`,
        errorMessage: $localize`Failed to delete user, check logs for details`,
        apiService: this.usersApi,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('clients-users/users'),
      }
    ));

    return actions;
  }

  getDetailsLink(): string {
    return this.config.getPanelUrl(`clients-users/users/${this.object.id}`);
  }

  getCardFields(): IDataField[] {
    const datePipe = new DateFormatterPipe(this.config);
    let clientDetails;
    if (this.object.clients.length === 1) {
      clientDetails = {
        name: $localize`Client`,
        value: this.object.clients[0].display
      };
    } else if (this.object.clients.length > 1) {
      clientDetails = {
        name: $localize`Clients count`,
        value: $localize`${this.object.clients.length} clients`
      };
    }
    const fields = [
      {
        name: $localize`ID`,
        value: `#${this.object.id.toString()}`,
      },
      {
        name: $localize`Last login`,
        value: this.object.last_login ? datePipe.toDateTime(this.object.last_login) : $localize`never`,
      }
    ];
    if (clientDetails) {
      fields.push(clientDetails);
    }
    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        const list = [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: UserDetailsOverviewComponent,
          },
        ] as IDetailsTab[];
        const user = this.object;
        if (!user.is_superuser && !user.is_staff) {
          list.push({
            tabName: $localize`Clients`,
            tabIdentifier: 'clients',
            component: UserDetailsClientsComponent,
          });
        }
        if (this.auth.userData.user.is_superuser) {
          list.push({
            tabName: $localize`User groups`,
            tabIdentifier: 'user-groups',
            component: UserDetailsGroupsComponent
          });
          if (!this.object.is_superuser) {
            list.push({
              tabName: $localize`Permissions`,
              tabIdentifier: 'permissions',
              component: UserDetailsPermissionsComponent
            });
          }
        }
        list.push.apply(list, [
          {
            tabName: $localize`Tickets`,
            tabIdentifier: 'tickets',
            featureName: 'plugins.tickets',
            component: UserDetailsTicketsComponent
          },
          {
            tabName: $localize`Activity log`,
            tabIdentifier: 'activity-log',
            component: UserDetailsLogComponent,
            featureName: 'utils.activitylog',
          },
          {
            tabName: $localize`Audit log`,
            tabIdentifier: 'audit-log',
            component: EntityAuditLogComponent,
            featureName: 'utils.activitylog',
            data: {
              entity_type: 'user'
            },
          }
        ]);
        return list;
      case 'edit':
      case 'create':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: UserEditFormComponent,
          },
        ];
    }
  }

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`clients-users/users`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Create`}));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`clients-users/users`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      default:
        break;
    }

    return actions;
  }

  getCardTags(): string[] {
    const tags: string[] = [];
    if (this.object.is_staff) {
      tags.push($localize`staff`);
    }
    if (this.object.is_superuser) {
      tags.push($localize`superuser`);
    }
    if (!this.object.is_active) {
      tags.push($localize`inactive`);
    }
    return tags;
  }
}
