import { Component, OnInit, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core';
import { SensorService } from '../../../../cores/services/sensor.service';
import { ApiResponse, ParameterSensor } from '../../../../cores/interface/sensor-data';
import { CommonModule } from '@angular/common';
import { Chart } from 'chart.js';
import { max } from 'date-fns';

@Component({
  selector: 'app-actualgraph',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './actualgraph.component.html',
  styleUrls: ['./actualgraph.component.scss']
})
export class ActualgraphComponent implements OnInit {
  @ViewChild('barChart') barChart!: ElementRef;
  selectedButton: string = 'npk1'; 
  greeting = '';
  
  chart: any;
  actualDataValues = { nitrogen: 0, phosphorus: 0, kalium: 0 };
  standardDataValues = {
    nitrogen: { min: 100, max: 200 },
    phosphorus: { min: 90, max: 125 },
    kalium: { min: 220, max: 240 }
  };

  constructor(
    private sensorService: SensorService, 
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    this.updateGreeting();
    this.loadData('npk1');  
  }

  ngAfterViewInit(): void {
    this.initChart();
  }

  initChart(): void {
    const minStandard = [
      this.standardDataValues.nitrogen.min,
      this.standardDataValues.phosphorus.min,
      this.standardDataValues.kalium.min
    ];

    const maxStandard = [
      this.standardDataValues.nitrogen.max,
      this.standardDataValues.phosphorus.max,
      this.standardDataValues.kalium.max
    ];

    this.chart = new Chart(this.barChart.nativeElement, {
      type: 'bar',
      data: {
        labels: ['Nitrogen', 'Phosphorus', 'Kalium'],
        datasets: [
          {
            label: 'Min Standard',
            backgroundColor: 'rgba(0, 0, 0, 0)',
            data: minStandard,
            borderWidth: 0
          },
          {
            label: 'Max Standard',
            backgroundColor: 'rgba(212, 231, 197)',
            data: maxStandard,
            borderWidth: 1
          },
          {
            label: 'Actual Data',
            type: 'scatter', 
            backgroundColor: 'rgba(18, 55, 42)',
            borderColor: 'rgba(18, 55, 10)',
            pointRadius: 5,
            pointHoverRadius: 7,
            data: [
              { x: 'Nitrogen', y: this.actualDataValues.nitrogen },
              { x: 'Phosphorus', y: this.actualDataValues.phosphorus },
              { x: 'Kalium', y: this.actualDataValues.kalium }
            ],
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          x: { stacked: true },
          y: {
            stacked: true,
            beginAtZero: false,
          }
        }
      }
    });
  }

  loadData(sensorType: string): void {
    this.selectedButton = sensorType;  

    this.sensorService.getLatestData().subscribe(
      (response: ApiResponse) => {
        if (response.statusCode === 200) {
          const selectedData = (response.data as { [key: string]: any[] })[sensorType];  

          if (selectedData && selectedData.length > 0) {
            const npkData: ParameterSensor = selectedData[0];

            this.actualDataValues = {
              nitrogen: npkData.soilnitrogen ?? 0,
              phosphorus: npkData.soilphosphorus ?? 0,
              kalium: npkData.soilpotassium ?? 0
            };
            this.updateChart();
          } else { 
          }
        } else {
          console.error('Error loading data: ', response.message);
        }
      },
      (error) => {
        console.error('Error loading data:', error);
        this.cdr.detectChanges();
      }
    );
  }

  updateChart(): void {
    if (this.chart) {
      this.chart.data.datasets[2].data = [
        { x: 'Nitrogen', y: this.actualDataValues.nitrogen },
        { x: 'Phosphorus', y: this.actualDataValues.phosphorus },
        { x: 'Kalium', y: this.actualDataValues.kalium }
      ];
      this.chart.update();
    }
  }

  updateGreeting(): void {
    const hour = new Date().getHours();
    this.greeting = hour < 12 ? 'Good Morning' : hour < 18 ? 'Good Afternoon' : 'Good Evening';
  }
}
