// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ConfigService } from '../../../providers/config.service';
import { LayoutService } from '../../../providers/layout.service';
import { FotovoltaicoService } from '../../../providers/fotovoltaico.service';
import { ImpiantoFv, PvDashboard } from '../../../models/fotovoltaico.model';

@Component({
	selector: 'app-fotovoltaico-cruscotto',
	templateUrl: './fotovoltaico-cruscotto.page.html',
	styleUrls: ['./fotovoltaico-cruscotto.page.scss'],
	standalone: false,
})
export class FotovoltaicoCruscottoPage {
	pvId = 0;
	cmp_id = 0;
	prt_id = 0;
	impianto: ImpiantoFv | null = null;
	dash: PvDashboard | null = null;
	loading = false;

	// data selezionata (ISO per ion-datetime, ridotta a yyyy-MM-dd per l'API)
	giornoIso: string = new Date().toISOString();
	todayMax: string = new Date().toISOString();
	datePickerOpen = false;

	private readonly mesi = ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'];

	// palette (nel portale arrivava dalle CSS var --kcs-*: qui valori fissi)
	private readonly accent = '#f5a623';
	private readonly success = '#4caf50';
	private readonly info = '#2196f3';
	private readonly textColor = '#6c757d';
	private readonly grid = 'rgba(128,128,128,0.15)';

	// dati grafici
	dayCurveData: any = null;
	dayCurveOptions: any = null;
	monthData: any = null;
	monthOptions: any = null;
	yearData: any = null;
	yearOptions: any = null;

	constructor(
		private route: ActivatedRoute,
		private config: ConfigService,
		public layout: LayoutService,
		private service: FotovoltaicoService,
	) {}

	ionViewWillEnter() {
		this.pvId = +(this.route.snapshot.paramMap.get('pv_id') as string);
		this.resolveIds();
		const listHref = `/portale/${this.prt_id}/company/${this.cmp_id}/service/fotovoltaico/list`;
		this.layout.setPageConfig({ title: 'Cruscotto', showBack: true, backButtonHref: listHref });
		this.service.GetImpianto(this.pvId).subscribe((res) => {
			this.impianto = res;
			if (res?.pv_denominazione) this.layout.setPageConfig({ title: res.pv_denominazione, showBack: true, backButtonHref: listHref });
		});
		this.loadDashboard();
	}

	private resolveIds() {
		let r: ActivatedRoute | null = this.route;
		while (r) {
			const pm = r.snapshot.paramMap;
			if (pm.get('cmp_id')) this.cmp_id = +(pm.get('cmp_id') as string);
			if (pm.get('prt_id')) this.prt_id = +(pm.get('prt_id') as string);
			r = r.parent;
		}
	}

	loadDashboard() {
		this.loading = true;
		const day = this.toYmd(new Date(this.giornoIso));
		this.service.GetDashboard(this.pvId, day).subscribe({
			next: (d) => {
				this.dash = d;
				this.buildCharts(d);
				this.loading = false;
			},
			error: () => {
				this.loading = false;
				this.config.presentToastError('Errore nel caricamento del cruscotto');
			},
		});
	}

	onDayChange(ev: any) {
		if (ev?.detail?.value) this.giornoIso = ev.detail.value;
		this.datePickerOpen = false;
		this.loadDashboard();
	}

	// percentuale produzione mese vs attesa
	get expectedPct(): number {
		if (!this.dash || !this.dash.kpi.expected_month_kwh) return 0;
		return Math.round((this.dash.kpi.month_kwh / this.dash.kpi.expected_month_kwh) * 100);
	}

	private buildCharts(d: PvDashboard) {
		// curva potenza del giorno (W)
		this.dayCurveData = {
			labels: (d.dayCurve || []).map((p) => this.hhmm(p.ts)),
			datasets: [
				{
					label: 'Potenza AC (W)',
					data: (d.dayCurve || []).map((p) => p.w),
					fill: true,
					borderColor: this.accent,
					backgroundColor: 'rgba(245,166,35,0.15)',
					tension: 0.3,
					pointRadius: 0,
					borderWidth: 2,
				},
			],
		};
		this.dayCurveOptions = this.baseOptions('W');

		// mese: kWh giorno per giorno
		this.monthData = {
			labels: (d.monthDaily || []).map((m) => this.dayNum(m.day)),
			datasets: [{ label: 'Energia (kWh)', data: (d.monthDaily || []).map((m) => this.round(m.kwh)), backgroundColor: this.info }],
		};
		this.monthOptions = this.baseOptions('kWh');

		// anno: prodotto vs atteso (kWh per mese)
		this.yearData = {
			labels: this.mesi,
			datasets: [
				{ type: 'bar', label: 'Prodotto (kWh)', data: (d.yearMonthly || []).map((m) => this.round(m.kwh)), backgroundColor: this.success },
				{ type: 'bar', label: 'Atteso (kWh)', data: (d.yearMonthly || []).map((m) => this.round(m.expected)), backgroundColor: 'rgba(128,128,128,0.35)' },
			],
		};
		this.yearOptions = this.baseOptions('kWh');
	}

	private round(n: number | null | undefined): number {
		return n ? Math.round(n * 100) / 100 : 0;
	}

	private baseOptions(unit: string): any {
		return {
			maintainAspectRatio: false,
			plugins: { legend: { labels: { color: this.textColor } } },
			scales: {
				x: { ticks: { color: this.textColor, maxTicksLimit: 12 }, grid: { color: this.grid } },
				y: { ticks: { color: this.textColor, callback: (v: any) => v + ' ' + unit }, grid: { color: this.grid }, beginAtZero: true },
			},
		};
	}

	// --- helper di formattazione data (senza dipendere dal locale Angular) ---
	private pad2(n: number): string {
		return n < 10 ? '0' + n : '' + n;
	}
	private toYmd(d: Date): string {
		return `${d.getFullYear()}-${this.pad2(d.getMonth() + 1)}-${this.pad2(d.getDate())}`;
	}
	private hhmm(ts: string): string {
		const d = new Date(ts);
		return `${this.pad2(d.getHours())}:${this.pad2(d.getMinutes())}`;
	}
	private dayNum(dayStr: string): string {
		const d = new Date(dayStr);
		return this.pad2(d.getDate());
	}
}
