<?php

namespace App\Filament\Pages;

use App\Filament\Widgets\ItemOverview;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms\Components\Select;
use Filament\Forms\Form;
use Filament\Pages\Dashboard\Concerns\HasFiltersForm;
use Filament\Pages\Page;
use Filament\Tables\Concerns\HasFilters;
use Illuminate\Support\Facades\Auth;
use Filament\Pages\Dashboard;

class HourlyProduction extends page
{
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static string $view = 'filament.pages.hourly-production';

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

    use HasFiltersForm;

    public $selectedPlant;
    public $selectedLine;
    public $selectedFilter = 'today';

   public function mount(): void
   {
      //session()->forget(['selected_plant', 'selected_line','selected_status']);
      session()->forget(['selected_plant', 'selected_line']);
      session()->forget(['select_plant', 'select_line']);
      $plantId = session('selected_plant', null); // Default to the first plant if not selected
      $lineId = session('selected_line', null);
      //$successStatus = session('selected_status', null);


       $this->filtersForm->fill([
           //'plant' => Plant::first()?->id // Default to first plant
           'plant' => $plantId,
           'line' => $lineId,
           //'success_status' => $successStatus,
       ]);
   }

   public function filtersForm(Form $form): Form
   {
       return $form
           ->statePath('filters')
           ->schema([

               Select::make('plant')
                    ->label('Select Plant')
                    ->reactive()
                    //->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) {
                        session(['selected_plant' => $state]);
                        // Clear production quantity Dashboard  session keys to avoid conflict
                        //session()->forget(['select_plant', 'select_line']);
                        $this->triggerChartUpdate();
                        $this->dispatch('filtersUpdated', [
                            'plant' => $state,
                            'line' => session('selected_line') ?? null,
                            'filter' => session('selected_filter') ?? 'today',
                        ]);
                    }),

               // Line Filter
               Select::make('line')
                   ->options(function ($get) {
                       $plantId = $get('plant');
                       return $plantId ? Plant::find($plantId)->getLineNames()->pluck('name', 'id') : [];
                   })
                   ->label('Select Line')
                   ->reactive()
                   ->afterStateUpdated(function ($state) {
                       session(['selected_line' => $state]);
                       $this->triggerChartUpdate();
                          $this->dispatch('filtersUpdated', [
                            'plant' => session('selected_plant') ?? null,
                            'line' => $state,
                            'filter' => session('selected_filter') ?? 'today',
                        ]);
                   }),

            // Select::make('success_status')
            //     ->label('Select Status')
            //     ->options([
            //         'Ok'     => 'Ok',
            //         'Not Ok' => 'Not Ok',
            //     ])
            //     ->reactive()
            //     ->afterStateUpdated(function ($state) {
            //         session(['selected_status' => $state]); // fixed typo
            //         //$this->dispatch('cumulativeChart'); // custom Livewire event
            //     }),
           ])
           ->columns(3);
   }

    // public function triggerChartUpdate(): void
    // {
    //     if (session()->has('selected_plant') && session()->has('selected_line') && session()->has('selected_status')) {
    //         $this->dispatch('filtersUpdated');
    //     }
    // }
    public function triggerChartUpdate(): void
    {
        if (session()->has('selected_plant') && session()->has('selected_line')) {
            $this->dispatch('filtersUpdated');
        }
    }



    public static function getNavigationLabel(): string
    {
        return 'Production Hourly Count';
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view production hourly count dashboard');
    }

    // public function getWidgets(): array
    // {
    //     return [
    //         ItemOverview::class,
    //     ];
    // }
}
