<?php

namespace App\Filament\Pages;

use App\Filament\Widgets\TrendLineChart;
use Filament\Facades\Filament;
use Filament\Pages\Page;
use Filament\Pages\Dashboard\Concerns\HasFiltersForm;
use App\Models\Plant;
use Filament\Forms\Components\Select;
use Filament\Forms\Form;
use Filament\Forms\Components\DateTimePicker;
use App\Models\MfmMeter;
use Illuminate\Support\Facades\Auth;

class TrendLineAnalysis extends Page
{
    use HasFiltersForm;
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static string $view = 'filament.pages.trend-line-analysis';

    protected static ?string $navigationGroup = 'EMS DashBoard';

     public function mount(): void
   {
       session()->forget(['selected_plant', 'selected_meter', 'from_datetime', 'to_datetime', 'parameter']);
       $this->filtersForm->fill([
            'selected_plant' => null,
            'selected_meter' => null,
            'from_datetime' => null,
            'to_datetime' => null,
            'parameter' => null,
       ]);
   }


    public function filtersForm(Form $form): Form
   {
       return $form
           ->statePath('filters')
           ->schema([
                DateTimePicker::make('from_datetime')
                    ->label('From DateTime')
                    ->required()
                    ->before('to_datetime')
                    ->reactive()
                    ->afterStateUpdated(function ($state) {
                        $formatted = \Carbon\Carbon::parse($state)->format('Y-m-d H:i:s');
                        session(['from_datetime' => $formatted]);
                    }),
                DateTimePicker::make('to_datetime')
                    ->label('To DateTime')
                    ->required()
                    ->after('from_datetime')
                    ->reactive()
                    ->afterStateUpdated(function ($state) {
                        $formatted = \Carbon\Carbon::parse($state)->format('Y-m-d H:i:s');
                        session(['to_datetime' => $formatted]);
                    }),
                Select::make('plant')
                    ->label('Select Plant')
                    ->reactive()
                    ->required()
                    //->options(Plant::pluck('name', 'id'))
                    ->options(function (callable $get) {
                        $userHas = Filament::auth()->user()->plant_id;
                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                    })
                    ->afterStateUpdated(function ($state, callable $set) {
                        session(['selected_plant' => $state]);
                        // When plant changes, also reset meter_name
                        $set('meter_name', null);
                        session(['selected_meter' => null]);
                        // dd($state);
                    }),
                Select::make('meter_name')
                    ->options(function ($get) {
                        $plantId = $get('plant');
                        // Return meter name/id pairs from mfm_meters where plant_id matches selected plant
                        return $plantId ? MfmMeter::where('plant_id', $plantId)->pluck('name', 'id') : [];
                    })
                    ->label('Select Meter')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function ($state) {
                        session(['selected_meter' => $state]);
                    }),
                Select::make('parameter')
                    ->options([
                        'Phase Voltage' => 'Phase Voltage',
                        'Line Voltage'  => 'Line Voltage',
                        'Current'       => 'Current',
                        'Active Power'  => 'Active Power',
                        'Power Factor'  => 'Power Factor',
                        'Units'         => 'Units',
                    ])
                    ->label('Select Parameter')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function ($state) {
                        session(['parameter' => $state]);
                    }),
           ])
           ->columns(5);
   }
    // public static function getNavigationLabel(): string
    // {
    //     return 'Trend Chart Analysis';
    // }
    // public function getHeading(): string
    // {
    //     return 'Trend Chart Analysis';
    // }


    public function getWidgets(): array
    {
        $widgets = [];

        if (TrendLineChart::canView()) {
            $widgets[] = TrendLineChart::class;
        }
        return $widgets;
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view ems trend line analysis dashboard');
    }
}
