import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { SidebarComponent } from './layouts/sidebar/sidebar.component';
import { GraphComponent } from './page/graph/graph.component';
import { CommonModule } from '@angular/common';
import { SensorService } from '../../cores/services/sensor.service';
import { SensorData, StatusRelay } from '../../cores/interface/sensor-data';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [RouterOutlet, SidebarComponent, CommonModule, GraphComponent],
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
  isLoaded: boolean = false; 
  hasError: boolean = false; 
  noData: boolean = false;
  selectedButton: string = '';
  latestUpdate: string = ''; 
  intervalId: any;
  greeting: string = '';
  sensorData: SensorData = {  
    dht: { lightIntensity: 0, temperature: 0, humidity: 0 },
    npk1: { temperature: 0, moisture: 0, conductivity: 0, ph: 0, nitrogen: 0, phosphorus: 0, potassium: 0 },
    npk2: { temperature: 0, moisture: 0, conductivity: 0, ph: 0, nitrogen: 0, phosphorus: 0, potassium: 0 }
  };
  relayStatus: StatusRelay[] = [];

  constructor(private apiService: SensorService, private toast: ToastrService) {}

  ngOnInit(): void {
    this.selectedButton = 'dht';
    this.updateGreeting();
    this.loadData();
  }

  ngOnDestroy(): void {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }


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

  selectSensor(param: string): void {
    this.selectedButton = param;
    if(param === 'relay'){
      this.loadRelayData();
    } else {
      this.loadData(); 
    }
  }

  loadData(): void {
    this.isLoaded = true;
    this.hasError = false;
    this.noData = false;

    this.apiService.getLatestData().subscribe(
      (response) => {
        const data = response.data;
        
        if ((!data.dht || data.dht.length === 0) &&
            (!data.npk1 || data.npk1.length === 0) &&
            (!data.npk2 || data.npk2.length === 0)) {
          this.noData = true; 
        } else {
          if (data.dht && data.dht.length > 0) {
            this.sensorData.dht = {
              lightIntensity: data.dht[0].viciluminosity ?? 0,
              temperature: data.dht[0].vicitemperature ?? 0,
              humidity: data.dht[0].vicihumidity ?? 0
            };
          }
  
          if (data.npk1 && data.npk1.length > 0) {
            this.sensorData.npk1 = {
              temperature: data.npk1[0].soiltemperature ?? 0,
              moisture: data.npk1[0].soilhumidity ?? 0,
              conductivity: data.npk1[0].soilconductivity ?? 0,
              ph: data.npk1[0].soilph ?? 0,
              nitrogen: data.npk1[0].soilnitrogen ?? 0,
              phosphorus: data.npk1[0].soilphosphorus ?? 0,
              potassium: data.npk1[0].soilpotassium ?? 0
            };
          }
  
          if (data.npk2 && data.npk2.length > 0) {
            this.sensorData.npk2 = {
              temperature: data.npk2[0].soiltemperature ?? 0,
              moisture: data.npk2[0].soilhumidity ?? 0,
              conductivity: data.npk2[0].soilconductivity ?? 0,
              ph: data.npk2[0].soilph ?? 0,
              nitrogen: data.npk2[0].soilnitrogen ?? 0,
              phosphorus: data.npk2[0].soilphosphorus ?? 0,
              potassium: data.npk2[0].soilpotassium ?? 0
            };
          }
        }
        this.isLoaded = false;
      },
      (error) => {
        this.isLoaded = false; 
        this.handleError(error);
      }
    );
  }

  loadRelayData(): void {
    this.isLoaded = true;
    this.hasError = false;
    
    this.apiService.getRelayStatus().subscribe(
      (response) => {
        if (Array.isArray(response.data) && response.data.length > 0) {
          this.relayStatus = response.data.map((relay) => ({
            id: relay.id,
            number: relay.number,
            enabled_at: relay.enabled_at,
            disabled_at: relay.disabled_at,
            created_at: relay.created_at,
            current_status: relay.current_status
          }));
          this.relayStatus.sort((a, b) => b.number - a.number);
  
          this.noData = false;
        } else {
          this.handleError({ message: 'No available relay data.' });
          this.noData = true;
        }
        this.isLoaded = false;
      },
      (error) => {
        this.isLoaded = false;
        this.handleError(error);
        this.hasError = true;
      }
    );
  }
  
  handleError(error: any): void {
    if (this.selectedButton === 'dht') {
      this.toast.error('Error fetching DHT sensor data. Please try again.', 'Error', { timeOut: 3000 });
    } else if (this.selectedButton === 'npk1') {
      this.toast.error('Error fetching NPK1 sensor data. Please try again.', 'Error', { timeOut: 3000 });
    } else if (this.selectedButton === 'npk2') {
      this.toast.error('Error fetching NPK2 sensor data. Please try again.', 'Error', { timeOut: 3000 });
    } else if (this.selectedButton === 'relay') {
      this.toast.error('Error fetching relay status. Please try again.', 'Error', { timeOut: 3000 });
    }
    this.hasError = true;
  }
}
