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 { CallbackAction } from '@objects-view/actions/callback-action';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { IOrderModel } from '@fleio-api/billing/model/order.model';
import { OrdersApiService } from '@fleio-api/billing/orders/order-api.service';
import { catchError, map } from 'rxjs/operators';
import { of } from 'rxjs';
import { NotificationService } from '@shared/ui-api/notification.service';
import { AddNewOrderFormComponent } from './tabs/add-new-order-form/add-new-order-form.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';
import { OrderDetailsOverviewComponent } from './tabs/order-details-overview/order-details-overview.component';

export class OrderUiService extends ObjectUIServiceBase<IOrderModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly ordersApiService: OrdersApiService;
  private datePipe: DateFormatterPipe;
  private notificationService: NotificationService;


  constructor(
    order: IOrderModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, ordersApiService: OrdersApiService,
    notificationService: NotificationService,
  ) {
    super(order, permissions, state);
    this.router = router;
    this.config = config;
    this.ordersApiService = ordersApiService;
    this.datePipe = new DateFormatterPipe(this.config);
    this.notificationService = notificationService;
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    switch (this.object.status) {
      case 'completed':
      case 'verified':
        return {type: StatusType.Defined, value: StatusValue.Active};
      case 'pending':
        return {type: StatusType.Defined, value: StatusValue.Suspended};
      case 'canceled':
        return {type: StatusType.Defined, value: StatusValue.Canceled};
      case 'fraud':
        return {type: StatusType.Defined, value: StatusValue.Error};
      default:
        return {type: StatusType.None, value: StatusValue.None};
    }
  }

  getTitle(): ITitle {
    const invoiceStatus = this.object.invoice ? this.object.invoice.status : $localize`n/a`;
    switch (this.state) {
      case 'details':
      case 'card-view':
        return {
          text: $localize`Order ${this.object.id}`,
          subText: `${this.object.status} - ${invoiceStatus}`.toLocaleUpperCase(),
        };
      case 'add-new':
        return {
          text: $localize`Create order`,
        };
      default:
        return {
          text: `${this.object.id}`,
        };
    }
  }

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

    if (this.object.status !== 'completed') {
      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'done'},
          name: $localize`Accept`,
          tooltip: $localize`Accept order`,
          noPermissions: !this.permissions['orders.accept'],
          refreshAfterExecute: true,
          confirmOptions: {
            confirm: true,
            title: $localize`Accept order`,
            message: $localize`Are you sure you want to accept order ${this.object.id}?`,
          },
          callback: () => this.ordersApiService.accept(this.object.id).pipe(
              catchError((error) => {
                if (error && error.error) {
                  if (error.error.messages && error.error.messages.length) {
                    let errorMessage = '';
                    if (error.error.detail) {
                      errorMessage = `${error.error.detail}: `;
                    }
                    errorMessage += error.error.messages[0];
                    this.notificationService.showMessage(errorMessage);
                  } else if (error.error.detail) {
                    this.notificationService.showMessage(error.error.detail);
                  }
                }
                return of(null);
              }), map((result) => {
                  if (result) {
                    return {success: true, message: $localize`Order accept scheduled`};
                  }
                }
              ))
        }
      ));
    }

    if (this.object.status !== 'cancel') {
      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'cancel'},
          name: $localize`Cancel`,
          noPermissions: !this.permissions['orders.cancel'],
          tooltip: $localize`Cancel order`,
          refreshAfterExecute: true,
          confirmOptions: {
            confirm: true,
            title: $localize`Cancel order`,
            message: $localize`Are you sure you want to cancel order ${this.object.id}?`,
          },
          callback: () => this.ordersApiService.cancel(this.object.id).pipe(map(() => ({success: true, message: $localize`Order canceled`})
            ))
        }
      ));
    }

    if (this.object.status !== 'verified') {
      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'verified'},
          name: $localize`Verify`,
          tooltip: $localize`Set as verified`,
          noPermissions: !this.permissions['orders.verify'],
          refreshAfterExecute: true,
          confirmOptions: {
            confirm: true,
            title: $localize`Set as verified`,
            message: $localize`Are you sure you want to set order ${this.object.id} as verified?`,
          },
          callback: () => this.ordersApiService.verify(this.object.id).pipe(map(() => ({success: true, message: $localize`Order set as verified`})
            ))
        }
      ));

    }
    if (this.object.status !== 'fraud') {
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: 'credit_card_off'},
          name: $localize`Set as fraud`,
          tooltip: $localize`Set as fraud`,
          refreshAfterExecute: true,
          noPermissions: !this.permissions['orders.fraud'],
          confirmOptions: {
            confirm: true,
            title: $localize`Set as fraud`,
            message: $localize`Are you sure you want to set order ${this.object.id} as fraud?`,
          },
          apiService: this.ordersApiService,
          apiAction: 'fraud',
          callType: CallType.Post,
        }
      ));
    }

    if (this.object.status !== 'pending') {
      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'undo'},
          name: $localize`Set back to pending`,
          tooltip: $localize`Set back to pending`,
          noPermissions: !this.permissions['orders.pending'],
          refreshAfterExecute: true,
          confirmOptions: {
            confirm: true,
            title: $localize`Set back to pending`,
            message: $localize`Are you sure you want to set order ${this.object.id} back to pending?`,
          },
          callback: () => this.ordersApiService.setPending(this.object.id).pipe(map(() => ({success: true, message: $localize`Order set as pending`})
            ))
        }
      ));
    }

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'credit_score'},
        name: $localize`Run fraud check`,
        tooltip: $localize`Run fraud check`,
        noPermissions: !this.permissions['orders.fraud_check'],
        refreshAfterExecute: true,
        confirmOptions: {
          confirm: true,
          title: $localize`Set as fraud`,
          message: $localize`Are you sure you want run fraud checks on order ${this.object.id}?`,
        },
        apiService: this.ordersApiService,
        apiAction: 'fraud_check',
        callType: CallType.Post,
      }
    ));

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        name: $localize`Delete`,
        tooltip: $localize`Delete order`,
        noPermissions: !this.permissions['orders.destroy'],
        refreshAfterExecute: true,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('orders'),
        confirmOptions: {
          confirm: true,
          title: $localize`Delete order`,
          message: $localize`Are you sure you want to delete order ${this.object.id}?`,
        },
        successMessage: $localize`Order deleted successfully`,
        apiService: this.ordersApiService,
        callType: CallType.Delete,
      }
    ));

    return actions;
  }

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

  getCardFields(): IDataField[] {
    const fields = [
      {
        name: $localize`Client`,
        value: this.object.client.display || $localize`n/a`,
      },
      {
        name: $localize`User`,
        value: this.object.user.display || $localize`n/a`,
      },
      {
        name: $localize`Order date`,
        value: this.datePipe.toDateTime(this.object.order_date),
      },
    ];

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: OrderDetailsOverviewComponent,
          },
          {
            tabName: $localize`Audit log`,
            tabIdentifier: 'audit-log',
            component: EntityAuditLogComponent,
            featureName: 'utils.activitylog',
            data: {
              entity_type: 'order'
            },
          }
        ];
      case 'add-new':
        return [
          {
            tabName: $localize`Create order`,
            tabIdentifier: 'create-order',
            component: AddNewOrderFormComponent,
          }
        ]
      default:
        return [];
    }
  }

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

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

    switch (this.state) {
      case 'add-new':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`orders`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Continue`}));
        break;
      default:
        break;
    }

    return actions;
  }
}
