<?php

namespace App\Filament\Widgets;

use App\Models\MfmReading;
use Carbon\Carbon;
use Filament\Widgets\ChartWidget;

class TrendLineChart extends ChartWidget
{
    protected static ?string $heading = 'Trend Line Analysis';

    protected static ?string $maxHeight = '420px';

    protected int|string|array $columnSpan = 12;

    protected function getData(): array
    {
        $fromDatetime = session('from_datetime');
        $toDatetime = session('to_datetime');
        $selectedPlant = session('selected_plant');
        $meterId = session('selected_meter');
        $parameter = session('parameter');

        if (empty($fromDatetime) || empty($toDatetime) || empty($selectedPlant) || empty($meterId) || empty($parameter)) {
            return [
                'labels' => [],
                'datasets' => [],
            ];
        }

        $fromDateTime = Carbon::parse($fromDatetime);
        $toDateTime = Carbon::parse($toDatetime);

        if ($fromDateTime->gt($toDateTime) || $fromDateTime->gt(now()) || $toDateTime->gt(now())) {
            return [
                'labels' => [],
                'datasets' => [],
            ];
        }

        $durationHours = $fromDateTime->diffInHours($toDateTime);
        if ($durationHours < 1 || $durationHours > 24) {
            return [
                'labels' => [],
                'datasets' => [],
            ];
        }

        $intervalCount = $durationHours > 12 ? 12 : 10;
        $intervalMinutes = $durationHours > 12 ? 120 : floor(($durationHours * 60) / $intervalCount);

        $labels = [];
        $columnMap = [];
        $datasetColors = [];
        $dataSeries = [];

        // Determine columns and labels based on selected parameter
        switch ($parameter) {
            case 'Phase Voltage':
                $columnMap = [
                    'voltage_ry' => 'Voltage RY Max',
                    'voltage_yb' => 'Voltage YB Max',
                    'voltage_br' => 'Voltage BR Max',
                    'frequency' => 'Frequency Max',
                ];
                $datasetColors = [
                    'voltage_ry' => 'rgba(255, 99, 132, 1)',    // red
                    'voltage_yb' => 'rgba(54, 162, 235, 1)',    // blue
                    'voltage_br' => 'rgba(255, 206, 86, 1)',    // yellow
                    'frequency'   => 'rgba(75, 192, 192, 1)',    // teal
                ];
                break;

            case 'Line Voltage':
                $columnMap = [
                    'voltage_r_n' => 'Voltage R-N Max',
                    'voltage_y_n' => 'Voltage Y-N Max',
                    'voltage_b_n' => 'Voltage B-N Max',
                    'frequency'   => 'Frequency Max',
                ];
                $datasetColors = [
                    'voltage_r_n' => 'rgba(153, 102, 255, 1)',  // purple
                    'voltage_y_n' => 'rgba(255, 159, 64, 1)',   // orange
                    'voltage_b_n' => 'rgba(0, 200, 83, 1)',     // green
                    'frequency'   => 'rgba(75, 192, 192, 1)',   // teal
                ];
                break;
            case 'Current':
                $columnMap = [
                    'current_r' => 'Current R Max',
                    'current_y' => 'Current Y Max',
                    'current_b' => 'Current B Max',
                    'current_n'   => 'Current N Max ',
                ];
                $datasetColors = [
                    'current_r' => 'rgba(153, 102, 255, 1)',  // purple
                    'current_y' => 'rgba(255, 159, 64, 1)',   // orange
                    'current_b' => 'rgba(0, 200, 83, 1)',     // green
                    'current_n'   => 'rgba(75, 192, 192, 1)',   // teal
                ];
                break;

            case 'Active Power':
                $columnMap = [
                    'active_power_r' => 'Active Pow R Max',
                    'active_power_y' => 'Active Pow Y Max',
                    'active_power_b' => 'Active Pow B Max',
                    'active_power_total'   => 'Active Pow Tot Max ',
                ];
                $datasetColors = [
                    'active_power_r' => 'rgba(153, 102, 255, 1)',  // purple
                    'active_power_y' => 'rgba(255, 159, 64, 1)',   // orange
                    'active_power_b' => 'rgba(0, 200, 83, 1)',     // green
                    'active_power_total'   => 'rgba(75, 192, 192, 1)',   // teal
                ];
                break;

            case 'Power Factor':
                $columnMap = [
                    'power_factor_r' => 'Power Fac R Max',
                    'power_factor_y' => 'Power Fac Y Max',
                    'power_factor_b' => 'Power Fac B Max',
                    'power_factor_total'   => 'Power Fac Tot Max ',
                ];
                $datasetColors = [
                    'power_factor_r' => 'rgba(153, 102, 255, 1)',  // purple
                    'power_factor_y' => 'rgba(255, 159, 64, 1)',   // orange
                    'power_factor_b' => 'rgba(0, 200, 83, 1)',     // green
                    'power_factor_total'   => 'rgba(75, 192, 192, 1)',   // teal
                ];
                break;

            case 'Units':
                $columnMap = [
                    'apparent_energy_received' => 'AppEneRec Max',
                    'reactive_energy_received' => 'ReacEneRec Max',
                    'active_energy_received' => 'ActiveEneRec Max',
                ];
                $datasetColors = [
                    'apparent_energy_received' => 'rgba(153, 102, 255, 1)',  // purple
                    'reactive_energy_received' => 'rgba(255, 159, 64, 1)',   // orange
                    'active_energy_received' => 'rgba(0, 200, 83, 1)',     // green
                ];
                break;

            default:
                return [
                    'labels' => [],
                    'datasets' => [],
                ];
        }

        // Initialize empty arrays for each data series
        foreach ($columnMap as $column => $label) {
            $dataSeries[$column] = [];
        }

        $current = $fromDateTime->copy();
        while ($current < $toDateTime) {
            $next = $current->copy()->addMinutes($intervalMinutes);

            $selectParts = [];
            foreach ($columnMap as $column => $label) {
                $selectParts[] = "MAX({$column}::double precision) as {$column}";
            }

            $readings = MfmReading::where('mfm_meter_id', $meterId)
                ->whereBetween('created_at', [$current, $next])
                ->selectRaw(implode(', ', $selectParts))
                ->first();

            $labels[] = $current->format('H:i');

            foreach ($columnMap as $column => $label) {
                $dataSeries[$column][] = round($readings->{$column} ?? 0, 2);
            }

            $current = $next;
        }

        // Construct dataset array
        $datasets = [];
        foreach ($columnMap as $column => $label) {
            $datasets[] = [
                'label' => $label,
                'data' => $dataSeries[$column],
                'borderColor' => $datasetColors[$column],
                'backgroundColor' => str_replace('1)', '0.2)', $datasetColors[$column]),
                'fill' => false,
                'tension' => 0.1,
            ];
        }

        return [
            'labels' => $labels,
            'datasets' => $datasets,
        ];
    }


    protected function getType(): string
    {
        return 'line';
    }
}
