import { Component, OnInit } from '@angular/core';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { MatDialog } from '@angular/material/dialog';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { ConfigService } from '@shared/config/config.service';
import { IConfigurationModel } from '@fleio-api/configurations/model/configuration.model';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { IClientCreditModel } from '@fleio-api/billing/model/client-credit.model';
import { IYesNoDialogResult } from '@shared/ui-api/interfaces/yes-no-dialog-result';
import { CurrencyFormatterPipe } from '@shared/ui/common/pipes/currency-formatter.pipe';
import { ChangeCreditDialogComponent } from '../../dialogs/change-credit-dialog/change-credit-dialog.component';
import {
  ChangeConfigurationDialogComponent
} from '../../dialogs/change-configuration-dialog/change-configuration-dialog.component';

@Component({
  selector: 'app-clients-details-overview',
  templateUrl: './client-details-overview.component.html',
  styleUrls: ['./client-details-overview.component.scss']
})
export class ClientDetailsOverviewComponent extends DetailsComponentBase<IClientModel> implements OnInit {
  changeConfigurationTooltip = $localize`Change configuration`;
  configuration: IConfigurationModel;
  infoIcon: IIcon = {
    name: 'info',
    verticalAlign: 'middle',
    fontSize: '20px',
    marginLeft: '5px',
  };
  editIcon: IIcon = {
    name: 'edit',
    verticalAlign: 'middle',
    fontSize: '20px',
    marginLeft: '5px',
  };
  deleteIcon: IIcon = {
    name: 'delete',
    verticalAlign: 'middle',
    fontSize: '20px',
    marginLeft: '5px',
  };
  currencyFormatter = new CurrencyFormatterPipe(this.config);

  constructor(
    private clientsApiService: ClientsApiService,
    private notificationService: NotificationService,
    private readonly matDialog: MatDialog,
    private refreshService: RefreshService,
    public config: ConfigService,
  ) {
    super();
  }

  ngOnInit(refreshTimerInterval?: number) {
    super.ngOnInit(refreshTimerInterval);
    this.loadConfiguration();
  }

  loadConfiguration() {
    this.clientsApiService.getConfiguration(this.object.id).subscribe(configuration => {
      this.configuration = configuration;
    });
  }

  updateUsage() {
    this.clientsApiService.updateUsage(this.object.id).subscribe(() => {
      this.notificationService.showMessage($localize`Usage updated`);
      this.refreshService.refresh();
    });
  }

  resetUsage() {
    this.notificationService.confirmDialog(
      {
        title: $localize`Reset usage`,
        importantMessage: $localize`This will permanently delete usage data.`,
        flags: [
          {
            id: 'delete_all_usage_data',
            message: $localize`Delete all usage data`,
            warningOnSelect: $localize`This will permanently delete service usage data (e.g., network traffic and resource usage logs for OpenStack services)`,
            selected: false,
          },
          {
            id: 'delete_all_service_cycles',
            message: $localize`Delete all service cycles`,
            warningOnSelect: $localize`This will permanently delete all service cycles`,
            selected: false,
          },
        ],
        disableConfirmTillFlagsSelected: ['delete_all_service_cycles', 'delete_all_usage_data'],
        disableConfirmTillFlagsSelectedAny: true,
      }
    ).subscribe(result => {
      if (result?.button === 'yes') {
        this.clientsApiService.resetUsage(this.object.id, result.flags).subscribe({
          next: () => {
            this.notificationService.showMessage($localize`Usage reset`);
            this.refreshService.refresh();
          }, error: error => {
            if (error && error.error) {
              this.notificationService.showMessage(error.error.detail);
            } else {
              this.notificationService.showMessage(
                $localize`Error when trying to reset usage. Check logs for more info.`
              );
            }
          }
        });
      }
    });
  }

  changeCredit(credit: IClientCreditModel) {
    this.matDialog.open(
      ChangeCreditDialogComponent, {
        data: {client: this.object, credit},
        autoFocus: false,
      }).afterClosed().subscribe(result => {
      if (result === true) {
        this.refreshService.refresh();
      }
    });
  }

  deleteCredit(credit: IClientCreditModel) {
    this.notificationService.confirmDialog({
      title: $localize`Delete credit`,
      message: $localize`Are you sure you want to delete credit for currency ${credit.currency}?`,
    }).subscribe((result: IYesNoDialogResult) => {
      if (result?.button === 'yes') {
        this.clientsApiService.deleteCredit(this.object.id, credit.id).subscribe({
          next: () => {
            this.notificationService.showMessage($localize`Credit deleted`);
            this.refreshService.refresh();
          },
          error: error => {
            this.notificationService.showMessage(error.error.detail);
          }
        })
      }
    });


  }

  changeConfiguration() {
    this.matDialog.open(
      ChangeConfigurationDialogComponent, {
        data: {
          client: this.object,
          configuration: this.configuration,
        },
        autoFocus: false,
      }
    ).afterClosed().subscribe(result => {
      if (result) {
        this.loadConfiguration();
      }
    });
  }

  getCreditTooltip(credit: IClientCreditModel) {
    const amount = this.currencyFormatter.transform(credit.amount, credit.currency, this.authSvc.currencyDisplayMode, this.authSvc.currencyDigitsInfo);
    const unpaid_usage = this.currencyFormatter.transform(credit.unpaid_usage, credit.currency, this.authSvc.currencyDisplayMode, this.authSvc.currencyDigitsInfo);
    return $localize`${amount} credit minus ${unpaid_usage} dynamic service usage`;
  }

  sortedCredits(): IClientCreditModel[] {
    return this.object.credits.sort(
      (a, b) => {
        if (a.currency === b.currency) {
          return 0;
        } else {
          if (a.currency == this.object.currency) {
            return -1;
          } else {
            return (a.id as number) - (b.id as number);
          }
        }
      }
    )
  }

  getUpdateUsageTooltip(): string {
    if (this.object.has_dynamic_usage_services) {
      return $localize`Update current credit based on dynamic usage service(s) cost`;
    } else {
      return $localize`Disabled since client has no dynamic usage services`;
    }
  }
}
