// angular
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { OnInit } from '@angular/core';
import { ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpParams } from '@angular/common/http';
import { DecimalPipe } from '@angular/common';

// libs
import {
	ChartComponent,
	ApexAxisChartSeries,
	ApexTitleSubtitle,
	ApexDataLabels,
	ApexChart,
	ApexPlotOptions,
	ApexLegend
} from "ng-apexcharts";
import moment from 'moment';

// app
import { ApiRoutes } from '../../api-routes';
import { DashboardInOutModel } from '../../model/dashboard.model';

export type ChartOptions = {
	series: ApexAxisChartSeries;
	chart: ApexChart;
	dataLabels: ApexDataLabels;
	title: ApexTitleSubtitle;
	plotOptions: ApexPlotOptions;
	legend: ApexLegend;
};

@Component({
	selector: 'app-dashboard-outcome',
	templateUrl: './dashboard.component.html',
	styleUrls: ['./dashboard.component.scss'],
})
export class DashboardOutcomeComponent implements OnInit {

	@ViewChild("chart") chart!: ChartComponent;
	public chartOptions!: Partial<ChartOptions>;
	dashboardModel?: DashboardInOutModel;
	total?: number;
	public dateFrom: Date = moment(new Date).add(-30, 'days').toDate();
	public dateTo: Date = moment(new Date).add(0, 'days').toDate();

	colors: string[] = ["#fd7f6f", "#7eb0d5", "#b2e061", "#bd7ebe", "#ffb55a", "#ffee65", "#beb9db", "#fdcce5", "#8bd3c7"];

	private readonly destroyRef = inject(DestroyRef);

	constructor(
		private httpClient: HttpClient,
		private _decimalPipe: DecimalPipe
	) {
	}

	ngOnInit() {
		this.loadData();
	}

	onChangePeriod(dates: Date[]) {
		this.dateFrom = dates[0];
		this.dateTo = dates[1];
		this.loadData();
	}

	onRightClick(event?: Event) {
		event?.preventDefault();
		this.loadData(true);
	}

	private loadData(update?: boolean, category?: string) {
		let params = new HttpParams()
			.set('from', moment(this.dateFrom).format('YYYY-MM-DD'))
			.set('to', moment(this.dateTo).format('YYYY-MM-DD'))
			.set('category', category || '')
			;

		this.httpClient
			.get<DashboardInOutModel>(ApiRoutes.DashboardOutcome, { params: params })
			.pipe(takeUntilDestroyed(this.destroyRef))
			.subscribe(response => {
				this.dashboardModel = response;

				var series = response.data.map(x => ({
					x: x.name + ' (' + (this._decimalPipe.transform(x.value, '1.2-2') || '') + ')',
					y: x.value
				}));
				var min = Math.min(...response.data.map(x => x.value));
				var max = Math.max(...response.data.map(x => x.value));
				var step = max / 10;
				var ranges = [];
				for (var i = 0; i < this.colors.length; i++) {
					ranges.push({
						from: i === 0 ? min : step * i,
						to: i === this.colors.length - 1 ? max + 10 : step * (i + 1),
						color: this.colors[this.colors.length - i - 1],
					});
				}

				this.total = response.data.reduce((sum, current) => sum + current.value, 0);

				if (update) {
					this.chart.updateSeries([{
						data: series
					}]);
				} else {
					this.setChartOptions(series, ranges);
				}
			});
	}

	private setChartOptions(data: any[], ranges: any[]) {
		var self = this;

		this.chartOptions = {
			series: [{
				data: data
			}],
			chart: {
				type: 'treemap',
				width: 600,
				height: 600,
				events: {
					click: function (event, chartContext, config) {
						var data = self.dashboardModel!.data[config.dataPointIndex];
						self.loadData(true, data.id);
					}
				}
			},
			plotOptions: {
				treemap: {
					enableShades: true,
					shadeIntensity: 0.5,
					reverseNegativeShade: true,
					colorScale: {
						ranges: ranges
					}
				}
			},
		};
	}
}
