<?php

namespace App\Filament\Pages;

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

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

    protected static string $view = 'filament.pages.invoice-data-dashboard';

    protected static ?string $navigationGroup = 'Invoice Management';

    public function mount(): void
    {
       session()->forget(['selected_plant','dist_channel']);
       $this->filtersForm->fill([
           'plant' => null,
           'distribution_channel' => null,
       ]);
    }

    public function filtersForm(Form $form): Form
    {
       return $form
           ->statePath('filters') // Store form state in 'filters'
           ->schema([
            Section::make('')
                ->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,callable $set) {
                        session(['selected_plant' => $state]);
                            $set('distribution_channel', null);
                            session()->forget('distribution_channel');
                    }),
                Select::make('distribution_channel')
                    ->label('Distribution Channel')
                    // ->options(function (callable $get) {
                    //     $plant = $get('plant');

                    //     if (!$plant) {
                    //         return [];
                    //     }

                    //     $options = InvoiceDataValidation::where('plant_id', $plant)
                    //         ->whereNotNull('distribution_channel_desc')
                    //         ->where('distribution_channel_desc', '!=', '')
                    //         ->select('distribution_channel_desc')
                    //         ->distinct()
                    //         ->pluck('distribution_channel_desc', 'distribution_channel_desc')
                    //         ->toArray();

                    //     $hasEmpty = InvoiceDataValidation::where('plant_id', $plant)
                    //         ->where(function ($q) {
                    //             $q->whereNull('distribution_channel_desc')
                    //             ->orWhere('distribution_channel_desc', '');
                    //         })
                    //         ->exists();

                    //     if ($hasEmpty) {
                    //         $options['Challan'] = 'Challan';
                    //     }

                    //     return $options;
                    // })
                     ->options(function (callable $get) {
                        $plant = $get('plant');

                        if (!$plant) {
                            return [];
                        }

                        // Fetch unique, non-empty distribution_channel_desc values
                        return InvoiceDataValidation::where('plant_id', $plant)
                            ->whereNotNull('distribution_channel_desc')
                            ->where('distribution_channel_desc', '!=', '')
                            ->distinct()
                            ->pluck('distribution_channel_desc', 'distribution_channel_desc')
                            ->toArray();
                    })
                    ->afterStateUpdated(callback: function ($state,callable $set) {
                        session(['dist_channel' => $state]);
                    })
                    ->reactive(),
                ])
                 ->columns(2),
            ]);
    }


    public static function getNavigationLabel(): string
    {
        return 'Invoice Data Dashboard';
    }

    public function getHeading(): string
    {
        return 'Invoice Data Dashboard';
    }

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

}
