<?php

namespace App\Filament\Pages;

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

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

    protected static string $view = 'filament.pages.production-line-stop-count';

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

    use HasFiltersForm;


    public function mount(): void
    {
        session()->forget(['selected_plant', 'selected_line']);
        $this->filtersForm->fill([
            //'plant' => Plant::first()?->id // Default to first plant
            'plant' => null,
            'line' => null,
        ]);
    }

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

                Select::make('plant')
                    ->label('Select Plant')
                    //->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();
                    })
                    ->reactive()
                    ->afterStateUpdated(function ($state) {
                        session(['selected_plant' => $state]);
                    }),

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

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


}
