<?php

namespace App\Filament\Pages;

use App\Filament\Widgets\ItemOverview;
use App\Models\Plant;
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 function mount(): void
   {
      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);

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

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

               Select::make('plant')
                   ->options(Plant::pluck('name', 'id'))
                   ->label('Select Plant')
                   ->reactive()
                   ->afterStateUpdated(function ($state) {
                       session(['selected_plant' => $state]);
                       // Clear production quantity Dashboard  session keys to avoid conflict
                      //session()->forget(['select_plant', 'select_line']);
                     $this->triggerChartUpdate();
                   }),

               // 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();
                   }),
           ])
           ->columns(2);
   }

    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,
        ];
    }
}
