<?php

namespace App\Filament\Resources;

use AlperenErsoy\FilamentExport\Actions\FilamentExportBulkAction as ActionsFilamentExportBulkAction;
use App\Filament\Exports\ProductionQuantityExporter;
use App\Filament\Imports\ProductionQuantityImporter;
use App\Filament\Resources\ProductionQuantityResource\Pages;
use App\Models\Block;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionQuantity;
use App\Models\Shift;
use Carbon\Carbon;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
// use Filament\Forms\Components\View;
use Livewire\Livewire;

class ProductionQuantityResource extends Resource
{
    protected static ?string $model = ProductionQuantity::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    // protected static ?string $navigationParentItem = 'Display Transactions';
    //  protected static string $view = 'filament.pages.hourly-production';

    protected static ?string $navigationGroup = 'Production';

    protected static ?int $navigationSort = 1;

    // public $plant_id;
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->relationship('plant', 'name')
                            ->required()
                            // ->nullable()
                            ->reactive()
                            // ->statePath('filters')
                            ->columnSpan(2) // 1
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            // ->default(fn () => optional(ProductionQuantity::latest()->first())->plant_id)
                            ->default(function () {
                                return optional(ProductionQuantity::latest()->first())->plant_id;
                            })
                            ->disabled(fn (Get $get) => ! empty($get('id')))
                            // ->afterStateUpdated(fn ($set) => $set('block_name', null))

                            ->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
                                $plantId = $get('plant_id');
                                $set('block_name', null);
                                if (! $plantId) {
                                    $set('pqPlantError', 'Please select a plant first.');

                                    return;
                                } else {
                                    $set('validationError', null);
                                    $set('pqPlantError', null);
                                }

                            })
                            // ->extraAttributes([
                            //     'x-on:change' => "
                            //         if (\$event.target.value) {
                            //             \$wire.dispatch('plant-updated', { plantId: \$event.target.value });
                            //         }
                            //     ",
                            // ])
                            // ->extraAttributes([
                            //     'x-on:change' => "\$wire.dispatch('filtersUpdated', { plantId: \$event.target.value })"
                            // ])
                            // ->extraAttributes([
                            //     'x-on:change' => "\$wire.set('plantId', \$event.target.value)"
                            // ])

                            // ->extraAttributes([
                            //     'x-on:change' => '$dispatch("plant-updated", { plantId: $event.target.value })',
                            //     // Dispatch Alpine event
                            // ])
                            // ->extraAttributes([
                            //     'x-on:change' => '$dispatch("plant-updated", { plantId: $event.target.value }); console.log("Plant updated:", $event.target.value);',
                            // ])
                            // ->extraAttributes([
                            //     'x-data' => '{ value: "" }',
                            //     'x-model' => 'value',
                            //     'wire:keydown.enter.prevent' => 'processSelectedPlant(value)', // Call Livewire method
                            // ])
                            ->hint(fn ($get) => $get('pqPlantError') ? $get('pqPlantError') : null)
                            ->hintColor('danger'),
                        Forms\Components\Select::make('block_name')
                            ->label('Block')
                            ->required()
                            // ->nullable()
                            ->columnSpan(1)
                            ->options(function (callable $get) {
                                if (! $get('plant_id')) {
                                    return [];
                                }

                                return Block::where('plant_id', $get('plant_id'))
                                    ->pluck('name', 'id')
                                    ->toArray();
                            })
                            ->reactive()
                            ->default(function () {
                                $latestShiftId = optional(ProductionQuantity::latest()->first())->shift_id;

                                return optional(Shift::where('id', $latestShiftId)->first())->block_id;
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                if ($get('id')) {
                                    $getShift = ProductionQuantity::where('id', $get('id'))->first();
                                    $getBlock = Shift::where('id', $getShift->shift_id)->first();
                                    if ($getBlock->block_id) {
                                        $set('block_name', $getBlock->block_id);
                                        $set('pqBlockError', null);
                                    }
                                }

                                $blockId = $get('block_name');
                                $set('shift_id', null);

                                // session(['select_plant' => $get('plant_id')]);
                                // session()->forget('select_line');

                                if (! $blockId) {
                                    $set('pqBlockError', 'Please select a block first.');

                                    return;
                                } else {
                                    $set('validationError', null);
                                    $set('pqBlockError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pqBlockError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pqBlockError') ? $get('pqBlockError') : null)
                            ->hintColor('danger'),
                        Forms\Components\Select::make('shift_id')
                            ->relationship('shift', 'name')
                            ->required()
                            ->columnSpan(1)
                            // ->nullable()
                            ->options(function (callable $get) {
                                if (! $get('plant_id') || ! $get('block_name')) {
                                    return [];
                                }

                                return Shift::where('plant_id', $get('plant_id'))
                                    ->where('block_id', $get('block_name'))
                                    ->pluck('name', 'id')
                                    ->toArray();
                            })
                            ->reactive()
                            ->default(function () {
                                return optional(ProductionQuantity::latest()->first())->shift_id;
                            })
                            // ->afterStateUpdated(fn ($set) => $set('line_id', null))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                if ($get('id')) {
                                    $getShift = ProductionQuantity::where('id', $get('id'))->first();
                                    if ($getShift->shift_id) {
                                        $set('shift_id', $getShift->shift_id);
                                        $set('pqShiftError', null);
                                    }
                                }

                                $curShiftId = $get('shift_id');
                                $set('line_id', null);

                                if (! $curShiftId) {
                                    $set('pqShiftError', 'Please select a shift first.');

                                    return;
                                } else {
                                    $set('validationError', null);
                                    $set('pqShiftError', null);
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pqShiftError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pqShiftError') ? $get('pqShiftError') : null)
                            ->hintColor('danger'),
                        Forms\Components\Select::make('line_id')
                            ->relationship('line', 'name')
                            ->required()
                            ->columnSpan(2)
                            // ->nullable()
                            // ->options(fn (callable $get) =>
                            // \App\Models\Line::where('plant_id', $get('plant_id'))
                            //     ->pluck('name', 'id')
                            //     ->toArray() // Convert collection to array
                            // )
                            ->options(function (callable $get) {
                                if (! $get('plant_id') || ! $get('block_name') || ! $get('shift_id')) {
                                    return [];
                                }

                                return Line::where('plant_id', $get('plant_id'))
                                    ->pluck('name', 'id')
                                    ->toArray();
                            })
                            ->reactive()
                            ->default(function () {
                                return optional(ProductionQuantity::latest()->first())->line_id;
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                if ($get('id')) {
                                    $getShift = ProductionQuantity::where('id', $get('id'))->first();
                                    if ($getShift->line_id) {
                                        $set('line_id', $getShift->line_id);
                                        $set('pqLineError', null);
                                    }
                                }

                                $lineId = $get('line_id');
                                $set('item_code', null);

                                //  session(['select_line' => $get('line_id')]);

                                session(['select_line' => $state]);

                                if (! $lineId) {
                                    $set('pqLineError', 'Please select a line first.');

                                    return;
                                } else {
                                    $set('validationError', null);
                                    $set('pqLineError', null);
                                    $set('item_id', null);
                                    // $set('item_description', null);
                                    $set('serial_number', null);

                                    $exists = ProductionQuantity::where('plant_id', $get('plant_id'))
                                        // ->where('shift_id', $get('shift_id'))
                                        ->where('line_id', $get('line_id'))
                                        ->latest()  // Orders by created_at DESC
                                        ->first();

                                    // if($exists)
                                    // {
                                    //     $existCode = Item::where('id', $exists->item_id)->first();
                                    //     $set('recent_qr', $existCode->code.'|'.$exists->serial_number);
                                    // }
                                    // else
                                    // {
                                    //     $set('recent_qr', null);
                                    // }
                                }
                            })
                            // ->extraAttributes([
                            //     'x-on:change' => "\$wire.dispatch('filtersUpdated')", // Dispatch Livewire event from Alpine.js
                            // ])
                            ->extraAttributes([
                                'x-on:change' => "\$wire.dispatch('filtersUpdated', { lineId: \$event.target.value })",
                            ])
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pqLineError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pqLineError') ? $get('pqLineError') : null)
                            ->hintColor('danger'),
                        // Forms\Components\Select::make('item_id')
                        //     ->label('Item Code')
                        //     ->relationship('item', 'code')
                        //     ->required(),
                        // // Forms\Components\TextInput::make('item_code')
                        // //     ->required()
                        // //     ->autocapitalize('item_code'),
                        // //     //->columnSpanFull(),
                        // Virtual field for code input (not stored in DB)
                        Forms\Components\TextInput::make('production_order')
                            ->label('Production Order')
                            ->reactive()
                            ->required()
                            ->minLength(7)
                            ->maxLength(14)
                            ->columnSpan(2)
                            // ->rules(['regex:/^[1-9][0-9]{6,}$/'])
                            // ->disabled(function ($get) {
                            //     return $get('item_code');
                            // })
                            // ->readOnly(fn (callable $get) => $get('item_code'))
                            ->default(function () {
                                // $latestProductionOrder = ProductionQuantity::latest()->first()->production_order;
                                // return $latestProductionOrder ?? null;
                                $latestProduction = ProductionQuantity::latest()->first();

                                return $latestProduction ? $latestProduction->production_order : null;
                            })
                            ->afterStateUpdated(function ($state, callable $get, callable $set): void {
                                if (! is_numeric($get('production_order')) || ! preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) {
                                    $set('item_code', null);
                                    $set('item_id', null);
                                    $set('serial_number', null);
                                    $set('production_order', null);
                                    $set('prodOrdError', 'Must be a numeric value with 7 to 14 digits.');
                                    $set('validationError', null);

                                    return;
                                } else {
                                    $set('item_code', null);
                                    $set('item_id', null);
                                    // $set('item_description', null);
                                    $set('serial_number', null);
                                    $set('production_order', $state);
                                    $set('prodOrdError', null);
                                    $set('validationError', null);

                                    return;
                                    // if (empty($state)) {
                                    // }
                                }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('prodOrdError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('prodOrdError') ? $get('prodOrdError') : null)
                            ->hintColor('danger'),
                        Forms\Components\TextInput::make('item_code')
                            ->label('Item Code')
                            // ->required()
                            ->reactive()
                            ->columnSpan(2)
                            ->autofocus(true)
                            // ->debounce(100)
                            // ->live()
                            // ->disabled(function ($get) {
                            //     return !$get('production_order');
                            // })

                            // ->submitOnEnter()
                            ->afterStateUpdated(function ($state, callable $get, callable $set) {
                                $set('success_msg', null);

                                // if (empty($state)) {
                                //     $set('item_id', null);
                                //     // $set('item_description', null);
                                //     $set('serial_number', null);
                                //     $set('validationError', null);
                                //     return;
                                // }
                                // else
                                // {
                                //     if (!$get('plant_id')) {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Please select a plant first.');
                                //         Notification::make()
                                //             ->title('Choose Plant')
                                //             ->body("Please select a plant first.")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }
                                //     else if (!$get('block_name')) {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Please select a block first.');
                                //         Notification::make()
                                //             ->title('Choose Block')
                                //             ->body("Please select a block first.")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }
                                //     else if (!$get('shift_id')) {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Please select a shift first.');
                                //         Notification::make()
                                //             ->title('Choose Shift')
                                //             ->body("Please select a shift first.")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }
                                //     else if (!$get('line_id')) {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Please select a line first.');
                                //         Notification::make()
                                //             ->title('Choose Line')
                                //             ->body("Please select a line first.")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }
                                //     else if (!$get('production_order')) {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Please scan the production order first.');
                                //         Notification::make()
                                //             ->title('Scan the production order first.')
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }

                                //     if(!is_numeric($get('production_order')))
                                //     {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Please scan the valid production order.');

                                //         Notification::make()
                                //             ->title('Invalid Production Order')
                                //             ->body("Must contain numeric values only.")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }
                                //     else if (!preg_match('/^[1-9][0-9]{6,}$/', $get('production_order')))
                                //     {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Please scan the valid production order first.');

                                //         Notification::make()
                                //             ->title('Invalid Production Order')
                                //             ->body("Must contain at least 7 digits.<br>Must start with a non-zero digit.")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }

                                //     // ********************************

                                //     $exists = \App\Models\ProductionPlan::where('plant_id', $get('plant_id'))
                                //         ->where('shift_id', $get('shift_id'))
                                //         ->where('line_id', $get('line_id'))
                                //         ->whereDate('created_at', today())
                                //         ->latest()
                                //         ->exists();

                                //     if ($exists)
                                //     {
                                //         $currentDate = date('Y-m-d');

                                //         $shiftId = Shift::where('id', $get('shift_id'))
                                //         ->first();

                                //         [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0];
                                //         $hRs = (int) $hRs;
                                //         //$miNs = (int) $miNs;-*/

                                //         $totalMinutes = $hRs * 60 + $miNs;

                                //         $from_dt = $currentDate . ' ' . $shiftId->start_time;

                                //         $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes"));

                                //         $currentDateTime = date('Y-m-d H:i:s');

                                //         // Check if current date time is within the range
                                //         if (!($currentDateTime >= $from_dt && $currentDateTime < $to_dt)) {
                                //             //echo "Choosed a valid shift...";
                                //             // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');

                                //             $set('item_code', null);
                                //             $set('item_id', null);
                                //             // $set('item_description', null);
                                //             $set('serial_number', null);
                                //             $set('validationError', 'Please select a valid shift.');
                                //             Notification::make()
                                //                 ->title('Invalid Shift')
                                //                 ->body("Please select a valid shift.")
                                //                 ->danger()
                                //                 ->send();
                                //             //$set('validationError', 'Curr.'.$currentDateTime.' (From: '.$from_dt.', To: '.$to_dt.')');
                                //             return;
                                //         }
                                //         else
                                //         {
                                //             $set('item_id', null);
                                //             // $set('item_description', null);
                                //             $set('serial_number', null);
                                //             $set('validationError', null);
                                //         }
                                //     }
                                //     else
                                //     {
                                //         $existShifts = \App\Models\ProductionPlan::where('plant_id', $get('plant_id'))
                                //         ->where('shift_id', $get('shift_id'))
                                //         ->where('line_id', $get('line_id'))
                                //         ->whereDate('created_at', Carbon::yesterday())
                                //         ->latest()
                                //         ->exists();

                                //         if ($existShifts) //if ($existShifts->count() > 0)
                                //         { // record exist on yesterday
                                //             //$currentDate = date('Y-m-d');
                                //             $yesterday = date('Y-m-d', strtotime('-1 days'));

                                //             $shiftId = Shift::where('id', $get('shift_id'))
                                //             ->first();

                                //             [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0];
                                //             $hRs = (int) $hRs;
                                //             //   $miNs = (int) $miNs;-*/

                                //             $totalMinutes = $hRs * 60 + $miNs;

                                //             $from_dt = $yesterday . ' ' . $shiftId->start_time;

                                //             $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes"));

                                //             $currentDateTime = date('Y-m-d H:i:s');

                                //             // Check if current date time is within the range
                                //             if ($currentDateTime >= $from_dt && $currentDateTime < $to_dt) {
                                //                 $set('item_id', null);
                                //                 // $set('item_description', null);
                                //                 $set('serial_number', null);
                                //                 $set('validationError', null);
                                //             }
                                //             else
                                //             {
                                //                 $currentDate = date('Y-m-d');

                                //                 $shiftId = Shift::where('id', $get('shift_id'))
                                //                 ->first();

                                //                 [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0];
                                //                 $hRs = (int) $hRs;
                                //                 //   $miNs = (int) $miNs;-*/

                                //                 $totalMinutes = $hRs * 60 + $miNs;

                                //                 $from_dt = $currentDate . ' ' . $shiftId->start_time;

                                //                 $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes"));

                                //                 $currentDateTime = date('Y-m-d H:i:s');

                                //                 // Check if current date time is within the range
                                //                 if ($currentDateTime >= $from_dt && $currentDateTime < $to_dt) {
                                //                     //echo "Choosed a valid shift...";
                                //                     // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');

                                //                     $set('item_code', null);
                                //                     $set('item_id', null);
                                //                     // $set('item_description', null);
                                //                     $set('serial_number', null);
                                //                     $set('validationError', 'Please set production plan first.');
                                //                     Notification::make()
                                //                         ->title('Plan Not Found')
                                //                         ->body("Please set production plan first.")
                                //                         ->danger()
                                //                         ->send();
                                //                     //$set('validationError', 'Curr.'.$currentDateTime.' (From: '.$from_dt.', To: '.$to_dt.')');
                                //                     return;
                                //                 }
                                //                 else
                                //                 {
                                //                     //echo "Choosed a valid shift...";
                                //                     // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');

                                //                     $set('item_code', null);
                                //                     $set('item_id', null);
                                //                     // $set('item_description', null);
                                //                     $set('serial_number', null);
                                //                     $set('validationError', 'Please select a valid shift.');
                                //                     Notification::make()
                                //                         ->title('Invalid Shift')
                                //                         ->body("Please select a valid shift.")
                                //                         ->danger()
                                //                         ->send();
                                //                     //$set('validationError', 'Curr.'.$currentDateTime.' (From: '.$from_dt.', To: '.$to_dt.')');
                                //                     return;
                                //                 }
                                //             }
                                //         }
                                //         else
                                //         { // record not exist on yesterday

                                //             //$currentDate = date('Y-m-d');
                                //             $yesterday = date('Y-m-d', strtotime('-1 days'));

                                //             $shiftId = Shift::where('id', $get('shift_id'))
                                //             ->first();

                                //             [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0];
                                //             $hRs = (int) $hRs;
                                //             //   $miNs = (int) $miNs;-*/

                                //             $totalMinutes = $hRs * 60 + $miNs;

                                //             $from_dt = $yesterday . ' ' . $shiftId->start_time;

                                //             $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes"));

                                //             $currentDateTime = date('Y-m-d H:i:s');

                                //             // Check if current date time is within the range
                                //             if ($currentDateTime >= $from_dt && $currentDateTime < $to_dt) {
                                //                 //echo "Choosed a valid shift...";
                                //                 // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');

                                //                 $set('item_code', null);
                                //                 $set('item_id', null);
                                //                 // $set('item_description', null);
                                //                 $set('serial_number', null);
                                //                 $set('validationError', 'Please set production plan first.');
                                //                 Notification::make()
                                //                     ->title('Plan Not Found')
                                //                     ->body("Please set production plan first.")
                                //                     ->danger()
                                //                     ->send();
                                //                 //$set('validationError', 'Curr.'.$currentDateTime.' (From: '.$from_dt.', To: '.$to_dt.')');
                                //                 return;
                                //             }
                                //             else
                                //             {
                                //                 $currentDate = date('Y-m-d');

                                //                 $shiftId = Shift::where('id', $get('shift_id'))
                                //                 ->first();

                                //                 [$hRs, $miNs] = explode('.', $shiftId->duration) + [0, 0];
                                //                 $hRs = (int) $hRs;
                                //                 //   $miNs = (int) $miNs;-*/

                                //                 $totalMinutes = $hRs * 60 + $miNs;

                                //                 $from_dt = $currentDate . ' ' . $shiftId->start_time;

                                //                 $to_dt = date('Y-m-d H:i:s', strtotime($from_dt . " + $totalMinutes minutes"));

                                //                 $currentDateTime = date('Y-m-d H:i:s');

                                //                 // Check if current date time is within the range
                                //                 if ($currentDateTime >= $from_dt && $currentDateTime < $to_dt) {
                                //                     //echo "Choosed a valid shift...";
                                //                     // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');

                                //                     $set('item_code', null);
                                //                     $set('item_id', null);
                                //                     // $set('item_description', null);
                                //                     $set('serial_number', null);
                                //                     $set('validationError', 'Please set production plan first.');
                                //                     Notification::make()
                                //                         ->title('Plan Not Found')
                                //                         ->body("Please set production plan first.")
                                //                         ->danger()
                                //                         ->send();
                                //                     //$set('validationError', 'Curr.'.$currentDateTime.' (From: '.$from_dt.', To: '.$to_dt.')');
                                //                     return;
                                //                 }
                                //                 else
                                //                 {
                                //                     //echo "Choosed a valid shift...";
                                //                     // $set('ppLineError', 'Valid (From: '.$from_dt.', To: '.$to_dt.')');

                                //                     $set('item_code', null);
                                //                     $set('item_id', null);
                                //                     // $set('item_description', null);
                                //                     $set('serial_number', null);
                                //                     $set('validationError', 'Please select a valid shift.');
                                //                     Notification::make()
                                //                         ->title('Invalid Shift')
                                //                         ->body("Please select a valid shift.")
                                //                         ->danger()
                                //                         ->send();
                                //                     //$set('validationError', 'Curr.'.$currentDateTime.' (From: '.$from_dt.', To: '.$to_dt.')');
                                //                     return;
                                //                 }
                                //             }
                                //         }
                                //     }

                                //     // ********************************

                                //     $set('item_id', null);
                                //     $set('serial_number', null);
                                //     $set('validationError', null);
                                // }

                                // if (!preg_match('/^[a-zA-Z0-9]{6,}+\|[1-9][a-zA-Z0-9]{8,}+(\|)?$/', $state)) {
                                //     if (strpos($state, '|') === false) {
                                //         $set('item_code', null);
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         $set('validationError', 'Scan valid QR code. (Ex: Item_Code|Serial_Number )');

                                //         Notification::make()
                                //             ->title('Invalid QR')
                                //             ->body("Scan the valid QR code.<br>(Ex: Item_Code|Serial_Number )")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }
                                //     else
                                //     {
                                //         $splits = explode('|', $state);
                                //         $iCode = trim($splits[0]);
                                //         $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                                //         if (!ctype_alnum($iCode)) {
                                //             $set('item_code', null);
                                //             $set('item_id', null);
                                //             // $set('item_description', null);
                                //             $set('serial_number', null);
                                //             $set('validationError', 'Item code must contain alpha-numeric values.');

                                //             Notification::make()
                                //                 ->title('Invalid Item Code')
                                //                 ->body("Item code must contain alpha-numeric values only.")
                                //                 ->danger()
                                //                 ->send();
                                //             return;
                                //         }
                                //         else if (strlen($iCode) < 6) {
                                //             $set('item_code', null);
                                //             $set('item_id', null);
                                //             // $set('item_description', null);
                                //             $set('serial_number', null);
                                //             $set('validationError', 'Item code must be at least 6 digits.');

                                //             Notification::make()
                                //                 ->title('Invalid Item Code')
                                //                 ->body("Item code must be at least 6 digits.")
                                //                 ->danger()
                                //                 ->send();
                                //             return;
                                //         }
                                //         else if (!ctype_alnum($sNumber)) {
                                //             $set('item_code', null);
                                //             $set('item_id', null);
                                //             // $set('item_description', null);
                                //             $set('serial_number', null);
                                //             $set('validationError', 'Serial Number must contain alpha-numeric values.');

                                //             Notification::make()
                                //                 ->title('Invalid Serial Number')
                                //                 ->body("Serial Number must contain alpha-numeric values only.")
                                //                 ->danger()
                                //                 ->duration(800)
                                //                 ->send();
                                //             return;
                                //         }
                                //         else if (strlen($sNumber) < 9) {
                                //             // $set('item_code', null);
                                //             $set('item_id', null);
                                //             // $set('item_description', null);
                                //             $set('serial_number', null);
                                //             $set('validationError', 'Serial Number must be at least 9 digits.');

                                //             Notification::make()
                                //                 ->title('Invalid Serial Number')
                                //                 ->body("Serial Number must be at least 9 digits.")
                                //                 ->danger()
                                //                 ->duration(800)
                                //                 ->send();
                                //             return;
                                //         }
                                //     }

                                //     $set('item_id', null);
                                //     // $set('item_description', null);
                                //     $set('serial_number', null);
                                //     $set('validationError', 'Scan valid QR code. (Ex: Item_Code|Serial_Number )');

                                //     Notification::make()
                                //         ->title('Invalid QR')
                                //         ->body("Scan the valid QR code.<br>(Ex: Item_Code|Serial_Number )")
                                //         ->danger()
                                //         ->send();
                                //     return;
                                // }
                                // else
                                // {
                                //     $set('validationError', null);
                                //     $set('item_id', null);
                                //     // $set('item_description', null);
                                //     $set('serial_number', null);
                                // }

                                // // Only search when all parent IDs are selected
                                // $parts = explode('|', $state);
                                // $itemCode = trim($parts[0]);
                                // $serialNumber = isset($parts[1]) ? trim($parts[1]) : null;

                                // // Fetch item using item code and plant_id
                                // $item = Item::where('code', $itemCode)
                                //     ->where('plant_id', $get('plant_id'))
                                //     ->first();

                                // if ($item)
                                // {
                                //     $sNo = ProductionQuantity::where('serial_number', $serialNumber)
                                //     // ->where('plant_id', $get('plant_id'))
                                //     ->exists();
                                //     if (!$sNo)
                                //     {
                                //         $set('success_msg', 'Y');
                                //         // if (preg_match('/\n/', $state)) {
                                //         //     dd($state.': Enter key pressed');

                                //             //$set('serial_number', $serialNumber);
                                //             $set('item_id', $item->id);
                                //             //$set('item_code', $itemCode);
                                //         // }
                                //         // if (str_ends_with($state, "\n")) {
                                //         //     // Enter key was pressed (newline character detected)
                                //         //     //$state = trim($state); // Remove the newline

                                //         //     dd($state.': Enter key pressed');
                                //         //     // Perform your custom logic here
                                //         //     // For example, you could trigger a form submission:
                                //         //     // $this->submit();

                                //         //     $set('serial_number', $serialNumber);
                                //         //     $set('item_id', $item->id);
                                //         //     $set('item_code', $itemCode);
                                //         //     // $set('item_description', $item->description);
                                //         // }
                                //     }
                                //     else
                                //     {
                                //         $set('validationError', 'Serial number already exist in database.');
                                //         ////$set('item_code', null); //246118|651616516155667
                                //         $set('item_id', null);
                                //         // $set('item_description', null);
                                //         $set('serial_number', null);
                                //         Notification::make()
                                //             ->title('Duplicate Serial Number')
                                //             ->body("Serial number already exist in database.")
                                //             ->danger()
                                //             ->send();
                                //         return;
                                //     }
                                // }
                                // else
                                // {
                                //     $set('item_code', null);
                                //     $set('item_id', null);
                                //     // $set('item_description', null);
                                //     $set('serial_number', null);
                                //     $set('validationError', 'Item code does not exist in master data.');

                                //     Notification::make()
                                //         ->title('Unknown Item Code')
                                //         ->body("Item code does not exist in master data.")
                                //         ->danger()
                                //         ->send();
                                //     return;
                                // }
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('validationError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('validationError') ? $get('validationError') : null)
                            ->hintColor('danger')
                            ->extraAttributes([
                                'x-data' => '{ value: "" }',
                                'x-model' => 'value',
                                'wire:keydown.enter.prevent' => 'processAllValues(value)',
                            ]),
                        Forms\Components\Hidden::make('serial_number')
                            ->required(),
                        Forms\Components\Hidden::make('success_msg')
                            ->required(),
                        Forms\Components\Hidden::make('item_id')
                            ->required(),
                        Forms\Components\Hidden::make('sap_msg_status'),
                        Forms\Components\Hidden::make('sap_msg_description'),
                        // ->unique(ignoreRecord: true),
                        // ->autocapitalize('characters'),
                        // ->columnSpanFull(),
                        Forms\Components\TextInput::make('recent_qr') // item_description
                            ->label('Last scanned QR')
                            ->reactive()
                            ->columnSpan(2)
                            ->default(function () {
                                // Get the latest 'item_id' foreign key from 'production_quantities' table
                                $latestProductionQuantity = ProductionQuantity::latest()->first();
                                if (! $latestProductionQuantity) {
                                    return null; // Return null if no production quantities exist
                                }

                                // Get the corresponding 'code' from 'items' table where 'id' matches 'item_id'
                                $itemCode = optional(Item::find($latestProductionQuantity->item_id))->code;

                                // Get the latest 'serial_number' from 'production_quantities' table
                                $serialNumber = $latestProductionQuantity->serial_number;

                                // Combine 'code' and 'serial_number' into the desired format
                                return $itemCode && $serialNumber ? "{$itemCode} | {$serialNumber}" : null;
                            })
                            ->readOnly(true),
                        Forms\Components\TextInput::make('id')
                            ->hidden()
                            ->readOnly(),
                        Forms\Components\Hidden::make('operator_id')
                            ->default(Filament::auth()->user()->name),
                    ])
                    ->columns(12), // 6
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                // Tables\Columns\TextColumn::make('id')
                //     ->label('ID')
                //     ->numeric()
                //     ->sortable(),
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('production_order')
                    ->label('Production Order')
                    ->alignCenter()
                    ->sortable(), // ->searchable(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->alignCenter()
                    ->sortable(), // ->searchable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->sortable(), // ->searchable(),
                Tables\Columns\TextColumn::make('item.uom')
                    ->label('Unit of Measure')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('shift.block.name')
                    ->label('Block')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('shift.name')
                    ->label('Shift')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('sap_msg_status')
                    ->label('SAP Message Status')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('sap_msg_description')
                    ->label('SAP Message Description')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('operator_id')
                    ->label('Operator ID')
                    ->alignCenter()
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        // plant
                        Select::make('Plant')
                            ->label('Select Plant')
                            ->nullable()
                            // ->options(function () {
                            //     return Plant::pluck('name', 'id'); // Assuming 'name' is the column you want to display
                            // })
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Line', null);
                                $set('Block', null);
                                $set('Shift', null);
                                $set('Item', null);
                                $set('sap_msg_status', null);
                                $set('operator_id', null);
                            }),

                        // line
                        Select::make('Line')
                            ->label('Select line')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

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

                                return Line::where('plant_id', $plantId)
                                    ->pluck('name', 'id');
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('operator_id', null);
                            }),

                        // block
                        Select::make('Block')
                            ->label('Select Block')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

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

                                return Block::where('plant_id', $get('Plant'))->pluck('name', 'id');
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Shift', null);
                                $set('operator_id', null);
                            }),

                        // shift
                        Select::make('Shift')
                            ->label('Select Shift')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                $blockId = $get('Block');

                                if (! $plantId || ! $blockId) {
                                    return []; // Return empty if plant or block is not selected
                                }

                                return Shift::where('plant_id', $plantId)
                                    ->where('block_id', $blockId)
                                    ->pluck('name', 'id');
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('operator_id', null);
                            }),

                        TextInput::make('production_order')
                            ->label('Production Order')
                            ->placeholder('Enter Production Order'),

                        TextInput::make('serial_number')
                            ->label('Serial Number')
                            ->placeholder(placeholder: 'Enter Serial Number'),

                        Select::make('Item')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

                                if (! $plantId) {
                                    return Item::whereHas('productionQuantities')->distinct()->pluck('code', 'id');
                                } else {
                                    return Item::whereHas('productionQuantities')->where('plant_id', $plantId)->distinct()->pluck('code', 'id');
                                }
                                // return Item::whereHas('stickerMasters', function ($query) use ($pId) {
                                //     if ($pId) {
                                //         $query->where('plant_id', $pId);
                                //     }
                                //     $query->whereHas('invoiceValidations');
                                // })->pluck('code', 'id');
                            })
                            ->searchable()
                            ->reactive(),

                        Select::make('sap_msg_status')
                            ->label('Select SAP Message Status')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

                                if (! $plantId) {
                                    return ProductionQuantity::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status');
                                } else {
                                    return ProductionQuantity::where('plant_id', $plantId)->whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status');
                                }
                            })
                            // ->options(QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status'))
                            ->reactive(),

                        Select::make('operator_id')
                            ->label('Created By')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                $lineId = $get('Line');
                                $shiftId = $get('Shift');
                                if (! $plantId && ! $lineId && ! $shiftId) {
                                    return ProductionQuantity::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                } elseif ($plantId && ! $lineId && ! $shiftId) {
                                    return ProductionQuantity::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                } elseif ($plantId && $lineId && ! $shiftId) {
                                    return ProductionQuantity::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                } elseif ($plantId && ! $lineId && $shiftId) {
                                    return ProductionQuantity::where('plant_id', $plantId)->where('shift_id', $shiftId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                } else { // if ($plantId && $lineId && $shiftId)
                                    return ProductionQuantity::where('plant_id', $plantId)->where('line_id', $lineId)->where('shift_id', $shiftId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                }
                            })
                            ->searchable()
                            ->reactive(),

                        DateTimePicker::make(name: 'created_from')
                            ->label('Created From')
                            ->placeholder(placeholder: 'Select From DateTime')
                            ->reactive()
                            ->native(false),

                        DateTimePicker::make('created_to')
                            ->label('Created To')
                            ->placeholder(placeholder: 'Select To DateTime')
                            ->reactive()
                            ->native(false),
                    ])
                    ->query(function ($query, array $data) {
                        if (empty($data['Plant']) && empty($data['Shift']) && empty($data['Line']) && empty($data['production_order']) && empty($data['serial_number']) && empty($data['Item']) && empty($data['operator_id']) && empty($data['sap_msg_status']) && empty($data['created_from']) && empty($data['created_to'])) {
                            return $query->whereRaw('1 = 0');
                        }

                        if (! empty($data['Plant'])) {// if ($plant = $data['Plant'] ?? null) {
                            $query->where('plant_id', $data['Plant']);
                        } else {
                            $userHas = Filament::auth()->user()->plant_id;

                            if ($userHas && strlen($userHas) > 0) {
                                return $query->whereRaw('1 = 0');
                            }
                        }

                        if (! empty($data['Shift'])) {// if ($shift = $data['Shift'] ?? null) {
                            $query->where('shift_id', $data['Shift']);
                        }

                        if (! empty($data['Line'])) {// if ($line = $data['Line'] ?? null) {
                            $query->where('line_id', $data['Line']);
                        }

                        if (! empty($data['production_order'])) {
                            $query->where('production_order', 'like', '%'.$data['production_order'].'%');
                        }

                        if (! empty($data['serial_number'])) {
                            $query->where('serial_number', 'like', '%'.$data['serial_number'].'%');
                        }

                        if (! empty($data['Item'])) {
                            $query->where('item_id', $data['Item']);
                        }

                        if (! empty($data['sap_msg_status'])) {
                            $query->where('sap_msg_status', $data['sap_msg_status']);
                        }

                        if (! empty($data['operator_id'])) {
                            $query->where('operator_id', $data['operator_id']);
                        }

                        if (! empty($data['created_from'])) {// if ($from = $data['created_from'] ?? null) {
                            $query->where('created_at', '>=', $data['created_from']);
                        }

                        if (! empty($data['created_to'])) {// if ($to = $data['created_to'] ?? null) {
                            $query->where('created_at', '<=', $data['created_to']);
                        }

                        // return $query;
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

                        if (! empty($data['Plant'])) {
                            $indicators[] = 'Plant: '.Plant::where('id', $data['Plant'])->value('name');
                        } else {
                            $userHas = Filament::auth()->user()->plant_id;

                            if ($userHas && strlen($userHas) > 0) {
                                return 'Plant: Choose plant to filter records.';
                            }
                        }

                        if (! empty($data['Shift'])) {
                            $indicators[] = 'Shift: '.Shift::where('id', $data['Shift'])->value('name');
                        }

                        if (! empty($data['Line'])) {
                            $indicators[] = 'Line: '.Line::where('id', $data['Line'])->value('name');
                        }

                        if (! empty($data['production_order'])) {
                            $indicators[] = 'Production Order: '.$data['production_order'];
                        }

                        if (! empty($data['serial_number'])) {
                            $indicators[] = 'Serial Number: '.$data['serial_number'];
                        }

                        if (! empty($data['Item'])) {
                            $indicators[] = 'Item Code: '.Item::where('id', $data['Item'])->value('code');
                        }

                        if (! empty($data['sap_msg_status'])) {
                            $indicators[] = 'SAP Message Status: '.$data['sap_msg_status'];
                        }

                        if (! empty($data['operator_id'])) {
                            $indicators[] = 'Created By: '.$data['operator_id'];
                        }

                        if (! empty($data['created_from'])) {
                            $indicators[] = 'From: '.$data['created_from'];
                        }

                        if (! empty($data['created_to'])) {
                            $indicators[] = 'To: '.$data['created_to'];
                        }

                        return $indicators;
                    }),
            ])
            ->filtersFormMaxHeight('280px')
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                    ActionsFilamentExportBulkAction::make('export')
                        ->defaultPageOrientation('landscape'),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Production Quantities')
                    ->color('warning')
                    ->importer(ProductionQuantityImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import production quantities');
                    }),
                // ->chunkSize(250),
                // ->maxRows(100000),
                ExportAction::make()
                    ->label('Export Production Quantities')
                    ->color('warning')
                    ->exporter(ProductionQuantityExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export production quantities');
                    }),
            ]);
    }

    // public function updatedDataPlantId($value)
    // {
    //     session(['select_plant' => $value]);
    //     $this->dispatch('filtersUpdated', $value);
    // }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProductionQuantities::route('/'),
            'create' => Pages\CreateProductionQuantity::route('/create'),
            'view' => Pages\ViewProductionQuantity::route('/{record}'),
            'edit' => Pages\EditProductionQuantity::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }

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

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

    // public function updatedDataPlantId($newPlantId)
    // {
    //     session(['select_plant' => $newPlantId]);

    //     $this->emit('filtersUpdated', $newPlantId);
    // }

    // public function mount(): void
    // {
    //     // Fetch the value from the database based on your conditions
    //     $recentScanned = ProductionQuantity::where('plant_id', $this->plant_id)
    //         // ->where('shift_id', $this->shift_id)
    //         // ->where('line_id', $this->line_id)
    //         // ->whereDate('created_at', today())
    //         ->latest()
    //         ->first();

    //     // Set the default value for 'plan_quantity' if a record exists
    //     if ($recentScanned) {
    //         $this->form()->fill([
    //             'recent_qr' => $recentScanned->plan_quantity,
    //         ]);
    //     }
    // }
}
