import { Component, OnInit } from '@angular/core';
import * as _moment from 'moment';
import {
  BillingHistoryApiService,
  BillingHistoryObjectList
} from '@fleio-api/billing/billing-history/billing-history-api.service';
import { IServiceDynamicUsageModel } from '@fleio-api/billing/model/service-dynamic-usage.model';
import { ConfigService } from '@shared/config/config.service';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { UntypedFormBuilder } from '@angular/forms';
import { PriceOverrideModel } from '@fleio-api/billing/model/service.model';

@Component({
  selector: 'app-billing-history-overview',
  templateUrl: './billing-history-overview.component.html',
  styleUrls: ['./billing-history-overview.component.scss']
})
export class BillingHistoryOverviewComponent implements OnInit {
  serviceUsages: BillingHistoryObjectList<IServiceDynamicUsageModel>;
  selectedServiceUsage: IServiceDynamicUsageModel;
  currentUsageId: FleioId;
  loading = false;
  lastUpdatedTxt;
  isFree = false;

  usageSelectForm = this.formBuilder.group({
    selectedUsageId: [''],
  });

  constructor(
    private billingHistoryApi: BillingHistoryApiService,
    public config: ConfigService,
    public formBuilder: UntypedFormBuilder,
  ) {
  }

  getCurrentUsage() {
    if (this.usageSelectForm.controls.selectedUsageId.value) {
      // load the selected service's billing data
      this.loadDynamicUsage(this.usageSelectForm.controls.selectedUsageId.value);
      return;
    }
    this.loading = true;
    this.billingHistoryApi.list({page_size: 1}).subscribe(dynamicUsage => {
      this.serviceUsages = dynamicUsage;
      if (!this.serviceUsages?.objects?.length) {
        // no data message will be shown, stop processing response
        return;
      }
      if (this.serviceUsages?.latest_data_from) {
        const currentTime = new Date();
        const humanizedTimeDiff = _moment.duration(
          // @ts-ignore
          currentTime - new Date(this.serviceUsages.latest_data_from)
        ).locale(this.config.locale).humanize();
        this.lastUpdatedTxt = $localize`Updated ${humanizedTimeDiff} ago`;
      } else {
        this.lastUpdatedTxt = null;
      }
      let currentUsageSet = false;
      if (this.currentUsageId) {
        const currentUsage = dynamicUsage.objects.find(u => u.id === this.currentUsageId);
        if (currentUsage) {
          this.usageSelectForm.controls.selectedUsageId.setValue(currentUsage.id);
          currentUsageSet = true;
        }
      }

      if (!currentUsageSet) {
        this.usageSelectForm.controls.selectedUsageId.setValue(dynamicUsage.objects[0].id);
      }
    }).add(() => {
      this.loading = false;
    });
  }

  loadDynamicUsage(id: FleioId) {
    this.loading = true;
    this.billingHistoryApi.get(id).subscribe(history => {
      this.selectedServiceUsage = history;
    }).add(() => {
      this.loading = false;
    });
  }

  getPrev() {
    if (this.selectedServiceUsage.previous_history) {
      this.loadDynamicUsage(this.selectedServiceUsage.previous_history);
    } else {
      console.error('Get prev called for service usage with no previous history');
    }
  }

  getNext() {
    if (this.selectedServiceUsage.next_history) {
      this.loadDynamicUsage(this.selectedServiceUsage.next_history);
    } else {
      this.getCurrentUsage();
    }
  }

  ngOnInit(): void {
    this.getCurrentUsage();
    this.usageSelectForm.controls.selectedUsageId.valueChanges.subscribe((id: FleioId) => {
      if (!this.currentUsageId) {
        // first land on page, we can find usage in the list that was loaded for the page
        this.selectedServiceUsage = this.serviceUsages.objects.find(u => u.id === id);
        this.currentUsageId = id;
      } else if (this.currentUsageId !== id) {
        // user changed service selection, re-load
        this.loadDynamicUsage(id);
      }
      this.currentUsageId = id;

      // find out if service is free
      const service = this.serviceUsages.available_services.find(
        availableService => availableService.related_dynamic_usage_id === id
      );
      this.isFree = service.price_override && service.price_override_model === PriceOverrideModel.FreeService;
    });
  }
}
