import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { ITicketModel } from '@fleio-api/plugins/tickets/model/ticket.model';
import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { ConfigService } from '@shared/config/config.service';
import { TicketsApiService } from '@fleio-api/plugins/tickets/tickets-api.service';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { IObjectStatus, StatusType, StatusValue } from '@objects-view/interfaces/object-status';
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 { IDataField } from '@objects-view/interfaces/card-data/data-field';
import { IDetailsTab } from '@objects-view/interfaces/details/details-tab';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { TicketsUtilsService } from '@fleio-api/plugins/tickets/tickets-utils.service';
import { ApiCallAction } from '@objects-view/actions/api-call-action';
import { TicketDetailsTabComponent } from '@shared/plugins/common-tabs/tickets/ticket-details-tab/ticket-details-tab.component';
import { TicketsOpenNewTabComponent } from './tabs/tickets-open-new-tab/tickets-open-new-tab.component';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';

export class TicketUiService extends ObjectUIServiceBase<ITicketModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly ticketsApiService: TicketsApiService;
  private readonly matDialog: MatDialog;
  private readonly ticketsUtilsService: TicketsUtilsService;
  private datePipe: DateFormatterPipe;

  public static getTicketStatus(object: ITicketModel): { type: StatusType; value: StatusValue } {
    if (object && object.status) {
      switch (object.status) {
        case 'open':
          return {type: StatusType.Defined, value: StatusValue.Active};
        case 'on hold':
          return {type: StatusType.Defined, value: StatusValue.Warning};
        case 'in progress':
          return {type: StatusType.Defined, value: StatusValue.Error};
        case 'done':
        case 'merged':
          return {type: StatusType.Defined, value: StatusValue.Disabled};
        case 'answered':
          return {type: StatusType.Defined, value: StatusValue.Active};
        case 'customer reply':
          return {type: StatusType.Defined, value: StatusValue.Waiting};
      }
    }
    return {type: StatusType.None, value: StatusValue.None};
  }

  constructor(
    ticket: ITicketModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, ticketsApiService: TicketsApiService, matDialog: MatDialog,
  ) {
    super(ticket, permissions, state);
    this.matDialog = matDialog;
    this.router = router;
    this.config = config;
    this.ticketsApiService = ticketsApiService;
    this.ticketsUtilsService = new TicketsUtilsService();
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    return TicketUiService.getTicketStatus(this.object);
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'details':
        return {
          text: $localize`#${this.object.id} - ${this.object.title}`,
          textAsHtml: true,
          subText: $localize`Status: ${this.object.status_display}`
        };
      case 'open-new-ticket':
        return {
          text: $localize`Open a new ticket`,
        };
      default:
        return {
          text: $localize`#${this.object.id} - ${this.object.title}`,
          textAsHtml: true,
          textBold: this.object.unread
        };
    }
  }

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

    if (this.object.status !== 'done') {
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: 'lock'},
          name: $localize`Close ticket`,
          tooltip: $localize`Close ticket`,
          confirmOptions: {
            confirm: true,
            title: $localize`Close ticket`,
            message: $localize`Close ticket?`,
          },
          apiService: this.ticketsApiService,
          apiAction: 'close_ticket',
        }
      ));
    }

    if (this.object.status === 'done') {
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: 'lock_open'},
          name: $localize`Reopen ticket`,
          tooltip: $localize`Reopen ticket`,
          confirmOptions: {
            confirm: true,
            title: $localize`Reopen ticket`,
            message: $localize`Reopen ticket?`,
          },
          apiService: this.ticketsApiService,
          apiAction: 'reopen_ticket',
        }
      ));
    }

    return actions;
  }

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

  getCardFields(): IDataField[] {
    let departmentRowDisplay = `${this.object.department_display}`;
    if (this.object && this.object.assigned_to) {
      departmentRowDisplay += ` (${this.object.assigned_to_display})`;
    }
    const lastReplyAt = this.ticketsUtilsService.formatLastReply(this.object.last_reply_at, this.config.locale);
    return [
      {
        name: $localize`Created at`,
        value: `${this.datePipe.toDateTime(this.object.created_at)}`
      },
      {
        name: $localize`Status`,
        value: `${this.object.status_display}`,
        valueTextAdditionalClasses: ['fl-bold'],
      },
      {
        name: $localize`Last reply at`,
        value: lastReplyAt
      },
      {
        name: $localize`Department`,
        value: departmentRowDisplay
      }
    ];
  }

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

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'open-new-ticket':
        return [
          {
            tabName: $localize`Open new ticket`,
            tabIdentifier: 'open-new-ticket',
            component: TicketsOpenNewTabComponent,
          },
        ];
      case 'details':
        return [
          {
            tabName: $localize`Details`,
            tabIdentifier: 'details',
            component: TicketDetailsTabComponent,
          },
        ];
      default:
        return [];
    }
  }

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

    switch (this.state) {
      case 'open-new-ticket':
        actions.push(new CallbackAction({name: $localize`Open ticket`}));
        break;
      case 'user-signatures':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`user/profile`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Add signature`}));
        actions.push(new CallbackAction({
          name: $localize`Save`,
          primary: true,
        }));
        break;
      case 'details':
        actions.push(new CallbackAction({
          name: $localize`Reply & close`,
          internalName: 'reply_and_close'
        }));
        actions.push(new CallbackAction({name: $localize`Reply`}));
        break;
      default:
        break;
    }

    return actions;
  }
}
