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 { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { CallbackAction } from '@objects-view/actions/callback-action';
import {
  ConfigureAutoInvoicingFormComponent
} from './tabs/configure-auto-invoicing-form/configure-auto-invoicing-form.component';
import {
  EnduserClientDetailOverviewComponent
} from './tabs/enduser-client-detail-overview/enduser-client-detail-overview.component';
import { ApiCallAction } from '@objects-view/actions/api-call-action';
import { of } from 'rxjs';
import { NotificationService } from '@shared/ui-api/notification.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { EnduserClientUsersTabComponent } from './tabs/enduser-client-users-tab/enduser-client-users-tab.component';
import {
  ClientDetailsEmailMessageLogComponent
} from '@shared/common-tabs/clients-users/clients/client-details-email-message-log/client-details-email-message-log.component';
import { OrderingService } from '@shared/ui-api/ordering.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import {
  ClientEditFormComponent
} from '@shared/common-tabs/clients-users/clients/client-edit-form/client-edit-form.component';

export class ClientUIService extends ObjectUIServiceBase<IClientModel> {

  // noinspection JSUnusedLocalSymbols
  constructor(
    client: IClientModel, permissions: IPermissionsModel, state: string,
    private readonly router: Router, private readonly config: ConfigService,
    private readonly clientsApi: ClientsApiService,
    private notificationsService: NotificationService,
    private refreshService: RefreshService,
    private orderingService: OrderingService,
  ) {
    super(client, permissions, state);
  }

  private isCurrentClient(): boolean {
    if (this.object?.id) {
      return this.object.id.toString() === this.config.activeClientId;
    } else {
      return null;
    }
  }

  getIcon(): IIcon {
    if (this.object && this.object.id) {
      return {
        name: '(avatar)',
        clientAvatar: this.object,
      };
    }
    return null;
  }

  getStatus(): IObjectStatus {
    return {type: StatusType.None, value: StatusValue.None};
  }

  getBorder(): string {
    if (this.config?.authService?.feature('clients&users.switch-client') && this.isCurrentClient()) {
      return `3px solid #4caf50`;
    } else {
      return null;
    }
  }

  getTitle(): ITitle {
    let title = this.object.name;
    let subText = '';
    if (this.object.company) {
      subText = title;
      title = this.object.company;
    }

    switch (this.state) {
      case 'auto-invoicing-settings':
        return {
          text: $localize`Configure auto invoicing for ${title}`,
          subText: subText,
        };

      case 'edit':
        return {
          text: $localize`Edit ${title}`,
          subText: subText,
        };

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

      default:
        if (this.config.activeClientId.toString() === this.object.id.toString()) {
          title += $localize` - current client`;
        }

        return {
          text: title,
          subText: subText,
          textTitle: title,
        };
    }
  }

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

    if (this.config.authService.feature('clients&users.switch-client')) {
      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'task_alt'},
          name: $localize`Select as current client`,
          tooltip: $localize`Select as current client`,
          confirmOptions: {
            confirm: false,
            title: null,
            message: null
          },
          disabled: this.isCurrentClient(),
          callback: () => {
            this.config.setActiveClientId(this.object.id.toString());
            if (this.objectsView) {
              const queryParams = this.orderingService.getQueryParams(`clients`);
              if (queryParams && queryParams.ordering) {
                window.location.href = this.config.getPanelUrl(`clients`) + `?ordering=${queryParams.ordering}`;
              } else {
                window.location.href = this.config.getPanelUrl(`clients`);
              }
            } else {
              window.location.href = this.config.getPanelUrl(`clients`, this.object.id);
            }
            return of(null);
          }
        }
      ));
    }

    if (this.config.authService.feature('billing.credit_auto_invoicing')) {
      actions.push(new RouterLinkAction({
          icon: {name: 'invoice', class: 'fl-icons'},
          name: $localize`Configure auto invoicing`,
          tooltip: $localize`Configure auto invoicing`,
          routerUrl: this.config.getPanelUrl(`clients/${this.object.id}/auto-invoicing`),
          router: this.router,
        }
      ));
    }

    if (this.hasOwnerRole()) {
      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'link_off'},
          tooltip: $localize`Dissociate`,
          name: $localize`Dissociate`,
          callback: () => {
            this.clientsApi.canDissociateAsOwner(this.object.id).subscribe(response => {
              if (response.can_dissociate) {
                this.notificationsService.confirmDialog({
                    title: $localize`Dissociate from client`,
                    message: $localize`Are you sure you want to dissociate from client ${this.object.name}?`,
                    importantMessage: $localize`Beware that you also have owner role on this client, however
                    you will be able to dissociate as other users with this role also exist.`,
                  }
                ).subscribe(result => {
                  if (result?.button === 'yes') {
                    this.clientsApi.dissociateFromClient(this.object.id).subscribe(() => {
                      this.notificationsService.showMessage('Dissociated.');
                      this.router.navigateByUrl(this.config.getPanelUrl('clients')).then(() => {
                      });
                    }, error => {
                      let message;
                      if (error?.error?.detail) {
                        message = error.error.detail;
                      } else {
                        message = $localize`Could not dissociate.`;
                      }
                      this.notificationsService.showMessage(message);
                    });
                  }
                });
              } else {
                this.notificationsService.showMessage($localize`Cannot dissociate as the last owner.`);
              }
            });
            return of(null);
          }
        }
      ));
    } else {
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: 'link_off'},
          name: $localize`Dissociate`,
          tooltip: $localize`Dissociate`,
          confirmOptions: {
            confirm: true,
            title: $localize`Dissociate from client`,
            message: $localize`Are you sure you want to dissociate from client ${this.object.name}?`
          },
          apiService: this.clientsApi,
          apiAction: 'dissociate_from_client',
        }
      ));
    }

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

    return actions;
  }

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

  getCardFields(): IDataField[] {
    const datePipe = new DateFormatterPipe(this.config);
    const roles = this.object.roles.map(role => role.display_name).join(',');
    return [
      {
        name: $localize`ID`,
        value: `#${this.object.id.toString()}`,
      },
      {
        name: $localize`Created at`,
        value: `${datePipe.toDateTime(this.object.date_created)}`
      },
      {
        name: $localize`Country`,
        value: `${this.object.country_name}`
      },
      {
        name: $localize`Roles`,
        value: roles,
      },
    ];
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'auto-invoicing-settings':
        return [
          {
            tabName: $localize`Configure auto invoicing for ${this.object.name}`,
            tabIdentifier: 'configure-auto-invoicing',
            component: ConfigureAutoInvoicingFormComponent
          }
        ];
      case 'details':
        const tabs = [
          {
            tabName: $localize`Details`,
            tabIdentifier: 'details',
            component: EnduserClientDetailOverviewComponent,
          },
        ] as any;
        if (this.hasOwnerRole()) {
          tabs.push({
            tabName: $localize`Users`,
            tabIdentifier: 'users',
            component: EnduserClientUsersTabComponent,
            featureName: 'clients&users.invitations',
          });
        }
        tabs.push({
          tabName: $localize`Email log`,
          tabIdentifier: 'email-log',
          featureName: 'logger.email-message-log',
          component: ClientDetailsEmailMessageLogComponent,
        });
        return tabs;
      case 'edit':
      case 'create':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: ClientEditFormComponent,
          },
        ];
    }
  }

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

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPanelHomeUrl(),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Add client billing information`}));
        break;
      case 'auto-invoicing-settings':
      case 'edit':
        let defaultFragment = null;
        if (this.config.authService && this.config.authService.userData && this.config.authService.userData.user &&
          this.config.authService.userData.user.clients && this.config.authService.userData.user.clients.length) {
          defaultFragment = `clients/${this.config.authService.userData.user.clients[0].id}`;
        }
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(defaultFragment),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      default:
        break;
    }

    return actions;
  }

  getObjectDetailsRefreshInterval(): number {
    switch (this.state) {
      case 'details':
        return this.config?.current?.settings?.refreshIntervals?.clientDetailsInterval;
      default:
        return null;
    }
  }

  private hasOwnerRole() {
    for (const role of this.object.roles) {
      if (role.name === 'Owner') {
        return true;
      }
    }
    return false;
  }
}
