<?php

namespace App\Filament\Resources;

use App\Filament\Exports\QualityValidationExporter;
use App\Filament\Imports\QualityValidationImporter;
use App\Filament\Resources\QualityValidationResource\Pages;
// use App\Jobs\SendInvalidQualityMailJob;
use App\Mail\InvalidQualityMail;
use App\Models\AlertMailRule;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\QualityValidation;
use App\Models\StickerMaster;
// use App\Models\User;
// use App\Notifications\StatusUpdated;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
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\Factories\Relationship;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Mail;

class QualityValidationResource extends Resource
{
    protected static ?string $model = QualityValidation::class;

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

    protected static ?string $navigationGroup = 'Display';

    public $isSubmitted = false;

    public $data = [];

    public static function form(Form $form): Form
    {
        return $form
            ->statePath('data')
            ->schema(components: [
                Forms\Components\Select::make('plant_id')
                    ->label('Plant Name')
                    ->relationship('plant', 'name')
                    ->reactive()
                    ->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();
                    })
                    ->afterStateUpdated(function (callable $set, callable $get, $state) {
                        $set('item_id', null);
                        $set('line_id', null);
                        $set('production_order', null);

                        $set('part_validation_type_options', []);
                        $set('part_validation_type', null);
                        $set('show_validation_image', false);
                        $set('validation1_image_url', null);

                        $set('plant', $state);

                        $pId = $get('plant_id');
                        if (! $pId) {
                            $set('pqPlantError', 'Please select a plant first.');
                        } else {
                            $set('pqPlantError', null);
                        }

                        $pId = $get('line_id');
                        if (! $pId) {
                            $set('pqLineError', null);
                        }
                    })
                    ->required()
                    // ->default(fn () => request()->query('plant_id'))
                    ->default(fn ($get) => $get('plant') ?? session('last_selected_plant_id'))
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('pqPlantError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('pqPlantError') ? $get('pqPlantError') : null)
                    ->hintColor('danger'),
                Forms\Components\Hidden::make('plant')
                    ->default(fn () => session('last_selected_plant_id'))
                    ->afterStateHydrated(function ($state, $set) {
                        if (! $state && request()->has('plant_id')) {
                            $set('plant_id', request()->get('plant_id'));
                        }
                    }),

                Forms\Components\Select::make('line_id')
                    ->label('Line Name')
                    ->relationship('line', titleAttribute: 'name')
                    ->reactive()
                    ->required()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            return [];
                        }

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

                        $set('line', $state);

                        $pId = $get('line_id');
                        if (! $pId) {
                            $set('pqLineError', 'Please select a line.');
                        } else {
                            $set('pqLineError', null);
                        }
                    })
                    ->default(fn ($get) => $get('line') ?? session('last_selected_line'))
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('pqLineError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('pqLineError') ? $get('pqLineError') : null)
                    ->hintColor('danger'),
                Forms\Components\Hidden::make('line')
                    ->default(fn () => session('last_selected_line'))
                    ->afterStateHydrated(function ($state, $set) {
                        if (! $state && request()->has('line_id')) {
                            $set('line_id', request()->get('line_id'));
                        }
                    }),
                Forms\Components\Hidden::make('sticker_master_id')
                    // ->relationship('stickerMaster', 'id')
                    ->required(),
                Forms\Components\Hidden::make('uom')
                    ->required(),
                Forms\Components\Hidden::make('sap_msg_status'),
                Forms\Components\Hidden::make('sap_msg_description'),
                Forms\Components\TextInput::make('production_order')
                    ->placeholder('Scan the valid Production Order')
                    ->minLength(7)
                    ->maxLength(14)
                    ->reactive()
                    ->readOnly(fn (callable $get) => $get('item_id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if (! is_numeric($get('production_order')) || ! preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) {
                            $set('prodOrdError', 'Must be a numeric value with 7 to 14 digits.');
                            $set('production_order', null);
                            $set('item_id', null);
                            $set('sticker_master_id', null);
                            $set('uom', null);
                            $set('serial_number', null);
                        } else {
                            $set('prodOrdError', null);
                            $set('production_order', $state);
                            $set('production', $state);
                        }
                    })
                    ->default(fn ($get) => $get('production') ?? session('last_selected_production'))
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('prodOrdError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('prodOrdError') ? $get('prodOrdError') : null)
                    ->hintColor('danger')
                    ->required(),

                Forms\Components\Hidden::make('production')
                    ->default(fn () => session('last_selected_production'))
                    ->afterStateHydrated(function ($state, $set) {
                        if (! $state && request()->has('production_order')) {
                            $set('production_order', request()->get('production_order'));
                        }
                    }),

                Forms\Components\Hidden::make('operator_id')
                    ->required()
                    ->default(Filament::auth()->user()->name),

                Forms\Components\Hidden::make('sap_msg_status')
                    ->default(null),

                Forms\Components\Hidden::make('sap_msg_description')
                    ->default(null),

                // Forms\Components\TextInput::make('name')
                //     ->required()
                //     ->autofocus()
                //     ->live(debounce: 600)
                //     ->afterStateUpdated(function ($state, callable $set, callable $get) {
                //         $set('email', $state . '@cripumps.com');
                //     })
                //     ->maxLength(255),
                // Forms\Components\TextInput::make('email')
                //     // ->email()
                //     ->unique(ignoreRecord: true)
                //     ->required()
                //     ->readOnly()
                //     // ->rule(function (callable $get) {
                //     //     return Rule::unique('users', 'email')
                //     //         ->ignore($get('id')); // Ignore current record during updates
                //     // })
                //     // ->dehydrated()
                //     //->prefix(fn ($get) => $get('name') ?? null)
                //     // ->suffix('@cripumps.com')
                //     ->maxLength(255),

                Forms\Components\TextInput::make('item_id')
                    ->label('Item Code')
                    // ->id('item_id')
                    ->placeholder('Scan the valid QR code')
                    ->reactive()
                    ->required()
                    ->autofocus()
                    ->live()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $pId = $get('line_id');
                        $set('part_validation_type', null);
                        $set('show_validation_image', false);
                        $set('validation1_image_url', null);

                        if (! $pId) {
                            $set('pqLineError', 'Please select a line.');
                        } else {
                            $set('pqLineError', null);
                        }

                        $pOrder = $get('production_order');
                        if (! $pOrder) {
                            $set('prodOrdError', "Production Order can't be empty.");
                            $set('production_order', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('validation1_image_url', null);
                        } else {
                            $set('prodOrdError', null);
                        }

                        $serialFields = [
                            'serial_number_motor_qr', 'serial_number_pump_qr', 'serial_number_pumpset_qr', 'pack_slip_motor_qr', 'pack_slip_pump_qr', 'pack_slip_pumpset_qr', 'name_plate_motor_qr', 'name_plate_pump_qr', 'name_plate_pumpset_qr', 'tube_sticker_motor_qr', 'tube_sticker_pump_qr', 'tube_sticker_pumpset_qr', 'warranty_card_qr',
                        ];

                        $set('serial_number', null);

                        $serialnumber = ['serial_number_motor_qr', 'serial_number_pump_qr', 'serial_number_pumpset_qr'];

                        $partValidationColumns = [
                            'part_validation1', 'part_validation2', 'part_validation3', 'part_validation4', 'part_validation5',
                        ];

                        foreach ($serialFields as $field) {
                            $set($field.'_visible', false);
                            $set($field, null);
                        }

                        foreach ($partValidationColumns as $column) {
                            $set($column.'_visible', false);
                            $set($column, null);
                        }

                        // Proceed with validation logic for new scanned QR code
                        if (! $state || trim($state) == '') {
                            $set('validationError', null);

                            return;
                        }

                        // // Check if QR format contains '|'
                        if (strpos($state, '|') == false) {
                            $set('validationError', 'Scan valid QR code. (Ex: Item_Code|Serial_Number)');
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);

                            return;
                        }

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

                            if (! ctype_alnum($iCode)) {
                                $set('validationError', 'Item code must contain alpha-numeric values.');
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('part_validation_type_options', []);
                                $set('validation1_image_url', null);

                                return;
                            } elseif (strlen($iCode) < 6) {
                                $set('validationError', 'Item code must be at least 6 digits.');
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('part_validation_type_options', []);
                                $set('validation1_image_url', null);

                                return;
                            } elseif (! ctype_alnum($sNumber)) {
                                $set('validationError', 'Serial Number must contain alpha-numeric values.');
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('part_validation_type_options', []);
                                $set('validation1_image_url', null);

                                return;
                            } elseif (strlen($sNumber) < 9) {
                                $set('validationError', 'Serial Number must be at least 9 digits.');
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('part_validation_type_options', []);
                                $set('validation1_image_url', null);

                                return;
                            }
                            // }

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

                        $parts = explode('|', $state);

                        $itemCode = trim($parts[0]); // Extract item code // 123456|123456789

                        $serialNumber = trim($parts[1]);

                        // Store serial number before resetting fields
                        $previousSerialNumber = $serialNumber;

                        $previousItemCode = $itemCode;

                        if (strlen($itemCode) < 6) {
                            $set('validationError', 'Item code must be at least 6 digits.');
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);

                            return;
                        } elseif (! ctype_alnum($itemCode)) {
                            $set('validationError', 'Item Code should contain alpha-numeric values.');
                            $set('item_id', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);

                            return;
                        } elseif ($serialNumber == '') {
                            $set('validationError', 'Waiting for full QR scan...');

                            return;
                        } elseif (strlen($serialNumber) < 9) {
                            $set('validationError', 'Serial Number must be at least 9 digits.');
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);

                            return;
                        } elseif (! ctype_alnum($serialNumber)) {
                            $set('validationError', 'Serial Number should contain alpha-numeric values.');
                            $set('item_id', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);

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

                        $plantId = $get('plant_id'); // Get selected plant

                        if (! $plantId) {
                            $set('validationError', 'Please select a plant first.');
                            $set('item_id', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);

                            return;
                        }
                        // Check if the item exists for the selected plant
                        $stickerMaster = StickerMaster::where('plant_id', $plantId)->whereHas('item', function ($query) use ($itemCode) {
                            $query->where('code', $itemCode);
                        })->first();

                        if (! $stickerMaster) {
                            $set('validationError', 'Item code does not exist in master data.');
                            $set('sticker_master_id', null);
                            $set('uom', null);
                            $set('serial_number', null);
                            $set('part_validation_type', null);
                            $set('show_validation_image', false);
                            $set('part_validation_type_options', []);
                            $set('validation1_image_url', null);

                            return;
                        } else {
                            if (! $stickerMaster->item->uom) {
                                $set('validationError', "Item code does not have 'UOM' in master data.");
                                $set('sticker_master_id', null);
                                $set('uom', null);
                                $set('serial_number', null);
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('validation1_image_url', null);

                                return;
                            } elseif (! is_numeric($get('production_order')) || ! preg_match('/^[1-9][0-9]{6,13}$/', $get('production_order'))) {
                                $set('prodOrdError', 'Must be a numeric value.');
                                $set('item_id', null);
                                $set('sticker_master_id', null);
                                $set('uom', null);
                                $set('serial_number', null);
                                $set('part_validation_type', null);
                                $set('show_validation_image', false);
                                $set('part_validation_type_options', []);
                                $set('validation1_image_url', null);

                                return;
                            }

                            $set('sticker_master_id', $stickerMaster->id);
                            $set('uom', $stickerMaster->item->uom);
                            $set('item_id', $itemCode);
                            // $set('serial_number', null);
                            // $set('serial_number', $serialNumber);
                        }
                        // Check if user input matches the database values
                        foreach ($partValidationColumns as $field) {
                            if ($get("{$field}_visible")) {
                                $userInput = $get($field);
                                $expectedValue = $stickerMaster->$field;

                                if ($userInput != null && $userInput != $expectedValue) {
                                    $set('validationError', "Invalid input for $field. Expected: $expectedValue");

                                    return; // Stop execution if any validation fails
                                }
                            }
                        }

                        $serialExists = QualityValidation::where('serial_number', $serialNumber)->where('plant_id', $plantId)->exists();

                        // $serialExists = QualityValidation::where(function ($query) use ($serialNumber, $serialFields) {
                        //     foreach ($serialFields as $column) {
                        //         $colFld  = $column;
                        //         if (str_ends_with($colFld, '_qr')) {
                        //             $colFld = substr($colFld, 0, -3);
                        //         }
                        //         $query->where($colFld, $serialNumber);
                        //     }
                        // })->exists();

                        if ($serialExists && ! $get('id')) {
                            $set('validationError', 'Serial number already exists in quality validation.');
                            // $set('item_id', "$itemCode|$previousSerialNumber");
                            // $set('item_id', null);
                            $set('sticker_master_id', null);
                            $set('uom', null);
                            $set('serial_number', null);

                            return;
                        }

                        // Clear validation error if all inputs match
                        $set('validationError', null);

                        // $visibleColumns = [];
                        // foreach ($serialFields as $column) {
                        //     if ($stickerMaster->$column == 1) {
                        //         $visibleColumns[] = $column;
                        //     }
                        // }

                        // $visiblePartValidations = [];
                        // foreach ($partValidationColumns as $column) {
                        //     if ($stickerMaster->$column != null) {
                        //         $visiblePartValidations[] = $column;
                        //     }
                        // }

                        foreach ($serialFields as $column) {

                            $colFld = $column;
                            if (str_ends_with($colFld, '_qr')) {
                                $colFld = substr($colFld, 0, -3);
                            }

                            if ($stickerMaster->$colFld != null) {
                                $set($column.'_visible', true);
                            } else {
                                $set($column.'_visible', false);
                            }
                        }

                        foreach ($partValidationColumns as $column) {
                            if ($stickerMaster->$column != null) {
                                $set($column.'_visible', true);
                            } else {
                                $set($column.'_visible', false);
                            }
                        }

                        // foreach ($serialnumber as $field) {
                        //     if ($get("{$field}_visible")) {
                        //         $set($field, $serialNumber);
                        //         $colFld = $field;
                        //         if (str_ends_with($colFld, '_qr')) {
                        //             $colFld = substr($colFld, 0, -3);
                        //         }
                        //         $set($colFld, '1');
                        //         break;
                        //     }
                        // }
                        $serialAssigned = false;

                        foreach ($serialFields as $column) {

                            $colFld = $column;

                            if (str_ends_with($colFld, '_qr')) {
                                $colFld = substr($colFld, 0, -3);
                            }

                            $count = (int) ($stickerMaster->$colFld ?? 0);

                            // visibility always
                            $set($column . '_count', $count);

                            $set($column . '_visible', $count > 0);

                            // assign serial only once
                            if (!$serialAssigned && $count > 0) {

                                // single textbox
                                if ($count == 1) {
                                    $set($column . '_1', $serialNumber);
                                }

                                // multiple textbox
                                if ($count > 1) {

                                    for ($i = 1; $i <= $count; $i++) {

                                        $set($column . '_' . $i, $serialNumber);
                                    }
                                }

                                $set($colFld, '1');

                                $serialAssigned = true;
                            }
                        }

                        $set('serial_number', $serialNumber);
                        // Find item based on scanned code
                        $item = Item::where('code', $itemCode)
                            ->where('plant_id', $plantId)->first();

                        if (! $item) {
                            $set('part_validation_type_options', []);
                            return;
                        }

                        // Find sticker master
                        $sticker = StickerMaster::where('plant_id', $plantId)->where('item_id', $item->id)->first();

                        if (! $sticker) {
                            $set('part_validation_type_options', []);
                            return;
                        }

                        // Build dynamic options
                        $options = [];

                        if (! empty($sticker->part_validation1)) {
                            $options['part_validation1'] = 'Part Validation 1';
                        }
                        if (! empty($sticker->part_validation2)) {
                            $options['part_validation2'] = 'Part Validation 2';
                        }
                        if (! empty($sticker->part_validation3)) {
                            $options['part_validation3'] = 'Part Validation 3';
                        }
                        if (! empty($sticker->part_validation4)) {
                            $options['part_validation4'] = 'Part Validation 4';
                        }

                        // Save options in hidden field
                        $set('part_validation_type_options', $options);

                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('validationError') ? 'border-red-500' : '',
                        'id' => 'item_id',
                        'onkeydown' => "if (event.key === 'Enter') { event.preventDefault(); event.stopPropagation(); return false; }",
                    ])
                    // ->extraAttributes(fn ($get) => [
                    //     'class' => $get('validationError') ? 'border-red-500' : '',
                    // ])
                    // ->extraAttributes([
                    //     'onkeydown' => "if (event.key == 'Enter') { event.preventDefault(); return false; }",
                    // ])
                    // ->extraAttributes([
                    //     'id' => 'item_id'
                    // ])
                    ->hint(fn ($get) => $get('validationError') ? $get('validationError') : null)
                    ->hintColor('danger'),

                // Forms\Components\Select::make('part_validation_type')
                //     ->reactive()
                //     ->label('Select Validation')
                //     ->options(function (callable $get) {

                //         $plantId = $get('plant_id');
                //         $itemId  = $get('item_id');

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

                //         $sticker = StickerMaster::where('plant_id', $plantId)
                //                     ->where('item_id', $itemId)
                //                     ->first();

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

                //         $options = [];

                //         if (!empty($sticker->part_validation1)) {
                //             $options['part_validation1'] = 'Part Validation 1';
                //         }

                //         if (!empty($sticker->part_validation2)) {
                //             $options['part_validation2'] = 'Part Validation 2';
                //         }

                //         if (!empty($sticker->part_validation3)) {
                //             $options['part_validation3'] = 'Part Validation 3';
                //         }

                //         if (!empty($sticker->part_validation4)) {
                //             $options['part_validation4'] = 'Part Validation 4';
                //         }

                //         // if (!empty($sticker->part_validation5)) {
                //         //     $options['part_validation5'] = 'Part Validation 5';
                //         // }

                //         return $options;
                //     })
                //     ->reactive()
                //     ->required(),

                Forms\Components\Hidden::make('part_validation_type_options')
                    ->default([])
                    ->reactive()
                    ->dehydrated(false),

                Forms\Components\Hidden::make('show_validation_image')
                    ->reactive()
                    ->default(false),

                // Forms\Components\Select::make('part_validation_type')
                //     ->label('Select Validation')
                //     ->reactive()
                //     ->options(fn (callable $get) => $get('part_validation_type_options') ?? [])
                //     ->required()
                //     ->visible(fn ($get) => !empty($get('part_validation_type_options')))
                //     ->afterStateUpdated(function ($state, callable $set) {
                //         // when user selects something new, hide the image
                //         $set('show_validation_image', false);
                //         $set('validation1_image_url', null);
                //     }),

                Forms\Components\Select::make('part_validation_type')
                    ->label('Select Validation')
                    ->reactive()
                    ->options(fn (callable $get) => $get('part_validation_type_options') ?? [])
                    ->afterStateUpdated(function ($state, callable $set) {
                        // when user selects something new, hide the image
                        $set('show_validation_image', false);
                        $set('validation1_image_url', null);
                    })
                    ->visible(fn ($get) => ! empty($get('part_validation_type_options')))
                    ->suffixAction(
                        Forms\Components\Actions\Action::make('toggleValidationImage')
                            ->icon(fn (callable $get) => $get('show_validation_image') ? 'heroicon-o-eye-slash' : 'heroicon-o-eye')
                            ->tooltip('View Validation Image')
                            ->action(function (callable $get, $set) {

                                $currentState = $get('show_validation_image');
                                $set('show_validation_image', ! $currentState);

                                if ($currentState == true) {
                                    $set('validation1_image_url', null);

                                    return;
                                }

                                $partvalidationType = $get('part_validation_type');
                                $plantId1 = $get('plant_id');

                                $plantCode1 = Plant::where('id', $plantId1)->value('code');

                                $itemState = $get('item_id');
                                $parts = explode('|', $itemState);
                                $itemCode = trim($parts[0]);

                                $itemId1 = Item::where('code', $itemCode)
                                    ->where('plant_id', $plantId1)
                                    ->first();

                                $itemId2 = $itemId1?->id;

                                $sticker = StickerMaster::where('plant_id', $plantId1)
                                    ->where('item_id', $itemId2)
                                    ->first();

                                if (! $sticker) {
                                    Notification::make()
                                        ->title('Sticker Master Missing')
                                        ->body('No Sticker Master found for selected Plant & Item.')
                                        ->danger()
                                        ->send();

                                    return;
                                }

                                $value = $sticker->{$partvalidationType};
                                $fileName = "{$value}.png";

                                $imageUrl = route('part.validation.image', [
                                    'filename' => $fileName,
                                ]);

                                $set('validation1_image_url', $imageUrl);
                            })
                    ),

                // Forms\Components\Actions::make([
                //     Forms\Components\Actions\Action::make('openValidation')
                //         ->label('Open/Close')
                //         ->button()
                //         ->color('primary')
                //         ->action(function (callable $get, $set) {

                //             $currentState = $get('show_validation_image');
                //             $set('show_validation_image', !$currentState);

                //             if ($currentState == true) {
                //                 $set('validation1_image_url', null);
                //                 return;
                //             }

                //             $partvalidationType = $get('part_validation_type');
                //             $plantId1 = $get('plant_id');

                //             $plantCode1 = Plant::where('id', $plantId1)->value('code');

                //             $itemState = $get('item_id');

                //             $parts = explode('|', $itemState);

                //             $itemCode = trim($parts[0]);

                //             $itemId1 = Item::where('code', $itemCode)
                //             ->where('plant_id', $plantId1)->first();

                //             $itemId2 = $itemId1?->id;

                //             $sticker = StickerMaster::where('plant_id', $plantId1)
                //             ->where('item_id', $itemId2)
                //             ->first();

                //             if (!$sticker) {
                //                 Notification::make()
                //                     ->title('Sticker Master Missing')
                //                     ->body('No Sticker Master found for selected Plant & Item.')
                //                     ->danger()
                //                     ->send();
                //                 return;
                //             }

                //             $value = $sticker->{$partvalidationType};

                //             $fileName = "{$value}.png";

                //             // Check existence
                //             $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCode1}/{$fileName}");

                //             // Generate URL through custom route
                //             $imageUrl = route('part.validation.image', [
                //                 'plant' => $plantCode1,
                //                 'filename' => $fileName
                //             ]);

                //             // Pass to state (for modal/view)
                //             $set('validation1_image_url', $imageUrl);

                //         }),
                //     ])
                // ->visible(fn ($get) => !empty($get('part_validation_type_options'))),

                Forms\Components\Hidden::make('validation1_image_url')
                    ->reactive(),

                Forms\Components\View::make('components.part-validation-error-icon')
                    ->statePath('validation1_image_url')   // bind state directly
                    ->visible(fn ($get) => $get('show_validation_image') == true)
                    ->reactive(),

                Forms\Components\Hidden::make('serial_number')
                    ->required(),

                Forms\Components\Hidden::make('serial_number_motor'),

                // Forms\Components\TextInput::make('serial_number_motor_qr')
                //     ->label('Serial Number Motor')
                //     ->reactive()
                //     ->readOnly(fn (callable $get) => ! $get('id'))
                //     ->hidden(fn (callable $get) => ! $get('serial_number_motor_qr_visible'))  // Controls visibility
                //     ->default(''),
                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('serial_number_motor_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("serial_number_motor_qr_$i")
                            ->label("Serial Number Motor $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("serial_number_motor_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("serial_number_motor_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("serial_number_motor_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("serial_number_motor_error_$i", 'Serial number does not match.');
                                        $set("serial_number_motor_qr_$i", null);
                                        return;
                                    }

                                    $set("serial_number_motor_qr_$i", $state);
                                    $set('serial_number_motor', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("serial_number_motor_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("serial_number_motor_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("serial_number_motor_error_$i", 'Serial number does not match.');
                                    $set("serial_number_motor_qr_$i", null);
                                    return;
                                }

                                $set("serial_number_motor_error_$i", null);
                                $set("serial_number_motor_qr_$i", $serialNumber);
                                $set('serial_number_motor', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("serial_number_motor_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("serial_number_motor_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                Forms\Components\Hidden::make('serial_number_pump'),

                // Forms\Components\TextInput::make('serial_number_pump_qr')
                //     ->label('Serial Number Pump')
                //     ->reactive()
                //     ->required()
                //     ->hidden(fn (callable $get) => ! $get('serial_number_pump_qr_visible'))
                //     ->default('')
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('serial_number_pump_error', null);

                //         if (empty($state)) {
                //             $set('serial_number_pump_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('serial_number_pump_error', 'Serial number does not match.');
                //                     $set('serial_number_pump_qr', null);

                //                     return;
                //                 } else {
                //                     $set('serial_number_pump_error', null);
                //                     $set('serial_number_pump_qr', $serialNumber);
                //                     $set('serial_number_pump', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('serial_number_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('serial_number_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('serial_number_pump_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('serial_number_pump_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('serial_number_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('serial_number_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('serial_number_pump_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('serial_number_pump_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);

                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('serial_number_pump_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('serial_number_pump_qr', $serialNumber);
                //         $set('serial_number_pump', '1');

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('serial_number_pump_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('serial_number_pump_error', 'Serial number does not match.');
                //             $set('serial_number_pump_qr', null);

                //             return;
                //         } else {
                //             $set('serial_number_pump_error', null);
                //             $set('serial_number_pump_qr', $serialNumber);
                //             $set('serial_number_pump', '1');
                //         }
                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('serial_number_pump_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('serial_number_pump_error') ? $get('serial_number_pump_error') : null)
                //     ->hintColor('danger'),


                Forms\Components\Group::make()
                    ->schema(function (callable $get) {

                        $fields = [];

                        $count = (int) ($get('serial_number_pump_qr_count') ?? 0);

                        for ($i = 1; $i <= $count; $i++) {

                            $fields[] = Forms\Components\TextInput::make("serial_number_pump_qr_$i")
                                ->label("Serial Number Pump $i")
                                ->reactive()
                                ->required()
                                ->default('')
                                ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                    $set("serial_number_pump_error_$i", null);

                                    if (empty($state)) {
                                        $set("serial_number_pump_error_$i", null);
                                        return;
                                    }

                                    if (strpos($state, '|') == false) {

                                        if (strlen($state) < 9) {
                                            $set("serial_number_pump_error_$i",'Serial Number must be at least 9 digits.');
                                            return;
                                        }

                                        if (!ctype_alnum($state)) {
                                            $set("serial_number_pump_error_$i",'Serial Number must contain alpha-numeric values.');
                                            return;
                                        }

                                        $visibleSerialNumber = $get('serial_number');

                                        if ($visibleSerialNumber != $state) {
                                            $set("serial_number_pump_error_$i",'Serial number does not match.');
                                            $set("serial_number_pump_qr_$i", null);
                                            return;
                                        }
                                        else{
                                            $set("serial_number_pump_qr_$i", $state);
                                            $set("serial_number_pump", '1');
                                            return;
                                        }
                                    }

                                    if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/',$state))
                                    {
                                        $set("serial_number_pump_error_$i",'Scan valid QR code.');
                                        return;
                                    }

                                    $parts = explode('|', $state);

                                    $itemCode = trim($parts[0]);

                                    $serialNumber = trim($parts[1]);

                                    $serialNumber = preg_replace('/\/[MmPpCc]$/','',$serialNumber);

                                    $expectedItemCode = trim((string) $get('item_id'));

                                    if ($itemCode != $expectedItemCode) {
                                        $set("serial_number_pump_error_$i",'Item code does not match.');
                                        return;
                                    }

                                    $visibleSerialNumber = $get('serial_number');

                                    if ($visibleSerialNumber != $serialNumber) {

                                        $set("serial_number_pump_error_$i",'Serial number does not match.');
                                        $set("serial_number_pump_qr_$i", null);
                                        return;
                                    }
                                    else
                                    {
                                        $set("serial_number_pump_error_$i", null);
                                        $set("serial_number_pump_qr_$i", $serialNumber);
                                        $set("serial_number_pump", '1');
                                    }
                                })
                                ->extraAttributes(fn ($get) => [
                                    'class' => $get("serial_number_pump_error_$i")
                                        ? 'border-red-500'
                                        : '',
                                ])
                                ->hint(fn ($get) => $get("serial_number_pump_error_$i"))
                                ->hintColor('danger');
                        }

                        return $fields;
                    })
                    ->columns(2),

                Forms\Components\Hidden::make('serial_number_pumpset'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('serial_number_pumpset_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("serial_number_pumpset_qr_$i")
                            ->label("Serial Number PumpSet $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("serial_number_pumpset_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("serial_number_pumpset_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("serial_number_pumpset_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("serial_number_pumpset_error_$i", 'Serial number does not match.');
                                        $set("serial_number_pumpset_qr_$i", null);
                                        return;
                                    }

                                    $set("serial_number_pumpset_qr_$i", $state);
                                    $set('serial_number_pumpset', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("serial_number_pumpset_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("serial_number_pumpset_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("serial_number_pumpset_error_$i", 'Serial number does not match.');
                                    $set("serial_number_pumpset_qr_$i", null);
                                    return;
                                }

                                $set("serial_number_pumpset_error_$i", null);
                                $set("serial_number_pumpset_qr_$i", $serialNumber);
                                $set('serial_number_pumpset', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("serial_number_pumpset_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("serial_number_pumpset_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('serial_number_pumpset_qr')
                //     ->label('Serial Number PumpSet')
                //     ->reactive()
                //     ->readOnly(fn (callable $get) => ! $get('id'))
                //     ->hidden(fn (callable $get) => ! $get('serial_number_pumpset_qr_visible'))
                //     ->default(''),

                Forms\Components\Hidden::make('pack_slip_motor'),

                // Forms\Components\TextInput::make('pack_slip_motor_qr')
                //     ->label('Pack Slip Motor')
                //     ->hidden(fn (callable $get) => ! $get('pack_slip_motor_qr_visible'))
                //     ->default('')
                //     ->reactive()
                //     ->required()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('pack_slip_motor_error', null);

                //         if (empty($state)) {
                //             $set('pack_slip_motor_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('pack_slip_motor_error', 'Serial number does not match.');
                //                     $set('pack_slip_motor_qr', null);

                //                     return;
                //                 } else {
                //                     $set('pack_slip_motor_error', null);
                //                     $set('pack_slip_motor_qr', $serialNumber);
                //                     $set('pack_slip_motor', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('pack_slip_motor_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('pack_slip_motor_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('pack_slip_motor_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('pack_slip_motor_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('pack_slip_motor_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('pack_slip_motor_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('pack_slip_motor_error', 'Scan valid QR code');

                //             return;
                //         } else {
                //             $set('pack_slip_motor_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor_qr')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);

                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('pack_slip_motor_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('pack_slip_motor_qr', $serialNumber);

                //         $set('pack_slip_motor', '1');

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('pack_slip_motor_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('pack_slip_motor_error', 'Serial number does not match.');
                //             $set('pack_slip_motor_qr', null);

                //             return;
                //         } else {
                //             $set('pack_slip_motor_error', null);
                //             $set('pack_slip_motor_qr', $serialNumber);
                //             $set('pack_slip_motor', '1');
                //         }
                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('pack_slip_motor_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('pack_slip_motor_error') ? $get('pack_slip_motor_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('pack_slip_motor_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("pack_slip_motor_qr_$i")
                            ->label("Pack Slip Motor $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("pack_slip_motor_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("pack_slip_motor_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("pack_slip_motor_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("pack_slip_motor_error_$i", 'Serial number does not match.');
                                        $set("pack_slip_motor_qr_$i", null);
                                        return;
                                    }

                                    $set("pack_slip_motor_qr_$i", $state);
                                    $set('pack_slip_motor', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("pack_slip_motor_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("pack_slip_motor_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("pack_slip_motor_error_$i", 'Serial number does not match.');
                                    $set("pack_slip_motor_qr_$i", null);
                                    return;
                                }

                                $set("pack_slip_motor_error_$i", null);
                                $set("pack_slip_motor_qr_$i", $serialNumber);
                                $set('pack_slip_motor', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("pack_slip_motor_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("pack_slip_motor_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                Forms\Components\Hidden::make('pack_slip_pump'),

                // Forms\Components\TextInput::make('pack_slip_pump_qr')
                //     ->label('Pack Slip Pump')
                //     ->hidden(fn (callable $get) => ! $get('pack_slip_pump_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('pack_slip_pump_error', null);

                //         if (empty($state)) {
                //             $set('pack_slip_pump_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('pack_slip_pump_error', 'Serial number does not match.');
                //                     $set('pack_slip_pump_qr', null);

                //                     return;
                //                 } else {
                //                     $set('pack_slip_pump_error', null);
                //                     $set('pack_slip_pump_qr', $serialNumber);
                //                     $set('pack_slip_pump', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('pack_slip_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('pack_slip_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('pack_slip_pump_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('pack_slip_pump_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('pack_slip_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('pack_slip_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('pack_slip_pump_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('pack_slip_pump_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);
                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('pack_slip_pump_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('pack_slip_pump_qr', $serialNumber);
                //         $set('pack_slip_pump', '1');

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('pack_slip_pump_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('pack_slip_pump_error', 'Serial number does not match.');
                //             $set('pack_slip_pump_qr', null);

                //             return;
                //         } else {
                //             $set('pack_slip_pump_error', null);
                //             $set('pack_slip_pump_qr', $serialNumber);
                //             $set('pack_slip_pump', '1');
                //         }
                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('pack_slip_pump_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('pack_slip_pump_error') ? $get('pack_slip_pump_error') : null)
                //     ->hintColor('danger'),
                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('pack_slip_pump_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("pack_slip_pump_qr_$i")
                            ->label("Pack Slip Pump $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("pack_slip_pump_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("pack_slip_pump_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("pack_slip_pump_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("pack_slip_pump_error_$i", 'Serial number does not match.');
                                        $set("pack_slip_pump_qr_$i", null);
                                        return;
                                    }

                                    $set("pack_slip_pump_qr_$i", $state);
                                    $set('pack_slip_pump', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("pack_slip_pump_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("pack_slip_pump_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("pack_slip_pump_error_$i", 'Serial number does not match.');
                                    $set("pack_slip_pump_qr_$i", null);
                                    return;
                                }

                                $set("pack_slip_pump_error_$i", null);
                                $set("pack_slip_pump_qr_$i", $serialNumber);
                                $set('pack_slip_pump', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("pack_slip_pump_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("pack_slip_pump_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                Forms\Components\Hidden::make('pack_slip_pumpset'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('pack_slip_pumpset_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("pack_slip_pumpset_qr_$i")
                            ->label("Pack Slip PumpSet $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("pack_slip_pumpset_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("pack_slip_pumpset_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("pack_slip_pumpset_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("pack_slip_pumpset_error_$i", 'Serial number does not match.');
                                        $set("pack_slip_pumpset_qr_$i", null);
                                        return;
                                    }

                                    $set("pack_slip_pumpset_qr_$i", $state);
                                    $set('pack_slip_pumpset', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("pack_slip_pumpset_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("pack_slip_pumpset_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("pack_slip_pumpset_error_$i", 'Serial number does not match.');
                                    $set("pack_slip_pumpset_qr_$i", null);
                                    return;
                                }

                                $set("pack_slip_pumpset_error_$i", null);
                                $set("pack_slip_pumpset_qr_$i", $serialNumber);
                                $set('pack_slip_pumpset', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("pack_slip_pumpset_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("pack_slip_pumpset_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('pack_slip_pumpset_qr')
                //     ->label('Pack Slip PumpSet')
                //     ->hidden(fn (callable $get) => ! $get('pack_slip_pumpset_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('pack_slip_pumpset_error', null);

                //         if (empty($state)) {
                //             $set('pack_slip_pumpset_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('pack_slip_pumpset_error', 'Serial number does not match.');
                //                     $set('pack_slip_pumpset_qr', null);

                //                     return;
                //                 } else {
                //                     $set('pack_slip_pumpset_error', null);
                //                     $set('pack_slip_pumpset_qr', $serialNumber);
                //                     $set('pack_slip_pumpset', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('pack_slip_pumpset_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('pack_slip_pumpset_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('pack_slip_pumpset_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('pack_slip_pumpset_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('pack_slip_pumpset_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('pack_slip_pumpset_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('pack_slip_pumpset_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('pack_slip_pumpset_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);

                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('pack_slip_pumpset_error', 'Item code does not match.');
                //             return;
                //         }

                //         $set('pack_slip_pumpset_qr', $serialNumber);
                //         $set('pack_slip_pumpset', '1');

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('pack_slip_pumpset_error', null);
                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('pack_slip_pumpset_error', 'Serial number does not match.');
                //             $set('pack_slip_pumpset_qr', null);
                //             return;
                //         } else {
                //             $set('pack_slip_pumpset_error', null);
                //             $set('pack_slip_pumpset_qr', $serialNumber);
                //             $set('pack_slip_pumpset', '1');
                //         }

                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('pack_slip_pumpset_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('pack_slip_pumpset_error') ? $get('pack_slip_pumpset_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Hidden::make('name_plate_motor'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('name_plate_motor_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("name_plate_motor_qr_$i")
                            ->label("Name Plate Motor $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("name_plate_motor_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("name_plate_motor_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("name_plate_motor_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("name_plate_motor_error_$i", 'Serial number does not match.');
                                        $set("name_plate_motor_qr_$i", null);
                                        return;
                                    }

                                    $set("name_plate_motor_qr_$i", $state);
                                    $set('name_plate_motor', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("name_plate_motor_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("name_plate_motor_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("name_plate_motor_error_$i", 'Serial number does not match.');
                                    $set("name_plate_motor_qr_$i", null);
                                    return;
                                }

                                $set("name_plate_motor_error_$i", null);
                                $set("name_plate_motor_qr_$i", $serialNumber);
                                $set('name_plate_motor', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("name_plate_motor_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("name_plate_motor_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('name_plate_motor_qr')
                //     ->label('Name Plate Motor')
                //     ->hidden(fn (callable $get) => ! $get('name_plate_motor_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('name_plate_motor_error', null);

                //         if (empty($state)) {
                //             $set('name_plate_motor_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('name_plate_motor_error', 'Serial number does not match.');
                //                     $set('name_plate_motor_qr', null);

                //                     return;
                //                 } else {
                //                     $set('name_plate_motor_error', null);
                //                     $set('name_plate_motor_qr', $serialNumber);
                //                     $set('name_plate_motor', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('name_plate_motor_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('name_plate_motor_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('name_plate_motor_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('name_plate_motor_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('name_plate_motor_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('name_plate_motor_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('name_plate_motor_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('name_plate_motor_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);
                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('name_plate_motor_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('name_plate_motor_error', $serialNumber);

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('name_plate_motor_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('name_plate_motor_error', 'Serial number does not match.');
                //             $set('name_plate_motor_qr', null);

                //             return;
                //         } else {
                //             $set('name_plate_motor_error', null);
                //             $set('name_plate_motor_qr', $serialNumber);
                //             $set('name_plate_motor', '1');
                //         }

                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('name_plate_motor_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('name_plate_motor_error') ? $get('name_plate_motor_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Hidden::make('name_plate_pump'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('name_plate_pump_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("name_plate_pump_qr_$i")
                            ->label("Name Plate Pump $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("name_plate_pump_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("name_plate_pump_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("name_plate_pump_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("name_plate_pump_error_$i", 'Serial number does not match.');
                                        $set("name_plate_pump_qr_$i", null);
                                        return;
                                    }

                                    $set("name_plate_pump_qr_$i", $state);
                                    $set('name_plate_pump', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("name_plate_pump_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("name_plate_pump_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("name_plate_pump_error_$i", 'Serial number does not match.');
                                    $set("name_plate_pump_qr_$i", null);
                                    return;
                                }

                                $set("name_plate_pump_error_$i", null);
                                $set("name_plate_pump_qr_$i", $serialNumber);
                                $set('name_plate_pump', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("name_plate_pump_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("name_plate_pump_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('name_plate_pump_qr')
                //     ->label('Name Plate Pump')
                //     ->hidden(fn (callable $get) => ! $get('name_plate_pump_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('name_plate_pump_error', null);

                //         if (empty($state)) {
                //             $set('name_plate_pump_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('name_plate_pump_error', 'Serial number does not match.');
                //                     $set('name_plate_pump_qr', null);

                //                     return;
                //                 } else {
                //                     $set('name_plate_pump_error', null);
                //                     $set('name_plate_pump_qr', $serialNumber);
                //                     $set('name_plate_pump', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('name_plate_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('name_plate_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('name_plate_pump_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('name_plate_pump_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('name_plate_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('name_plate_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('name_plate_pump_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('name_plate_pump_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);
                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('name_plate_pump_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('name_plate_pump_error', $serialNumber);

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('name_plate_pump_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('name_plate_pump_error', 'Serial number does not match.');
                //             $set('name_plate_pump_qr', null);

                //             return;
                //         } else {
                //             $set('name_plate_pump_error', null);
                //             $set('name_plate_pump_qr', $serialNumber);
                //             $set('name_plate_pump', '1');
                //         }

                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('name_plate_pump_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('name_plate_pump_error') ? $get('name_plate_pump_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Hidden::make('name_plate_pumpset'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('name_plate_pumpset_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("name_plate_pumpset_qr_$i")
                            ->label("Name Plate PumpSet $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("name_plate_pumpset_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("name_plate_pumpset_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("name_plate_pumpset_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("name_plate_pumpset_error_$i", 'Serial number does not match.');
                                        $set("name_plate_pumpset_qr_$i", null);
                                        return;
                                    }

                                    $set("name_plate_pumpset_qr_$i", $state);
                                    $set('name_plate_pumpset', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("name_plate_pumpset_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("name_plate_pumpset_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("name_plate_pumpset_error_$i", 'Serial number does not match.');
                                    $set("name_plate_pumpset_qr_$i", null);
                                    return;
                                }

                                $set("name_plate_pumpset_error_$i", null);
                                $set("name_plate_pumpset_qr_$i", $serialNumber);
                                $set('name_plate_pumpset', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("name_plate_pumpset_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("name_plate_pumpset_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('name_plate_pumpset_qr')
                //     ->label('Name Plate PumpSet')
                //     ->hidden(fn (callable $get) => ! $get('name_plate_pumpset_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('name_plate_pumpset_error', null);

                //         if (empty($state)) {
                //             $set('name_plate_pumpset_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('name_plate_pumpset_error', 'Serial number does not match.');
                //                     $set('name_plate_pumpset_qr', null);

                //                     return;
                //                 } else {
                //                     $set('name_plate_pumpset_error', null);
                //                     $set('name_plate_pumpset_qr', $serialNumber);
                //                     $set('name_plate_pumpset', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('name_plate_pumpset_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('name_plate_pumpset_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('name_plate_pumpset_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('name_plate_pumpset_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('name_plate_pumpset_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('name_plate_pumpset_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('name_plate_pumpset_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('name_plate_pumpset_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);
                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('name_plate_pumpset_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('name_plate_pumpset_error', $serialNumber);

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('name_plate_pumpset_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('name_plate_pumpset_error', 'Serial number does not match.');
                //             $set('name_plate_pumpset_qr', null);

                //             return;
                //         } else {
                //             $set('name_plate_pumpset_error', null);
                //             $set('name_plate_pumpset_qr', $serialNumber);
                //             $set('name_plate_pumpset', '1');
                //         }

                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('name_plate_pumpset_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('name_plate_pumpset_error') ? $get('name_plate_pumpset_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Hidden::make('tube_sticker_motor'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('tube_sticker_motor_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("tube_sticker_motor_qr_$i")
                            ->label("Tube Sticker Motor $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("tube_sticker_motor_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("tube_sticker_motor_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("tube_sticker_motor_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("tube_sticker_motor_error_$i", 'Serial number does not match.');
                                        $set("tube_sticker_motor_qr_$i", null);
                                        return;
                                    }

                                    $set("tube_sticker_motor_qr_$i", $state);
                                    $set('tube_sticker_motor', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("tube_sticker_motor_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("tube_sticker_motor_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("tube_sticker_motor_error_$i", 'Serial number does not match.');
                                    $set("tube_sticker_motor_qr_$i", null);
                                    return;
                                }

                                $set("tube_sticker_motor_error_$i", null);
                                $set("tube_sticker_motor_qr_$i", $serialNumber);
                                $set('tube_sticker_motor', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("tube_sticker_motor_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("tube_sticker_motor_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('tube_sticker_motor_qr')
                //     ->label('Tube Sticker Motor')
                //     ->hidden(fn (callable $get) => ! $get('tube_sticker_motor_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('tube_sticker_motor_error', null);

                //         // $mPorder = $get('production_order');

                //         // $mPlantId = $get('plant_id');
                //         // $plant = Plant::find($mPlantId);
                //         // $plantCodePart4 = $plant?->code;

                //         // $mlineId = $get('line_id');

                //         // $mLine = Line::find($mlineId);
                //         // $mLinePart = $mLine?->name;

                //         if (empty($state)) {
                //             $set('tube_sticker_motor_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('tube_sticker_motor_error', 'Serial number does not match.');
                //                     $set('tube_sticker_motor_qr', null);

                //                     return;
                //                 } else {
                //                     $set('tube_sticker_motor_error', null);
                //                     $set('tube_sticker_motor_qr', $serialNumber);
                //                     $set('tube_sticker_motor', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('tube_sticker_motor_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('tube_sticker_motor_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('tube_sticker_motor_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('tube_sticker_motor_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('tube_sticker_motor_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('tube_sticker_motor_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('tube_sticker_motor_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('tube_sticker_motor_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);
                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('tube_sticker_motor_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('tube_sticker_motor_error', $serialNumber);

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('tube_sticker_motor_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('tube_sticker_motor_error', 'Serial number does not match.');

                //             // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                //             // $mPlantName = $mailData['plant_name'];
                //             // $emails = $mailData['emails'];
                //             // $mUserName = Filament::auth()->user()->name;

                //             // if (!empty($emails))
                //             // {
                //             //     //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                //             //     Mail::to($emails)->send(
                //             //         new InvalidQualityMail($state, $mPorder, $mPlantName,$mLinePart, $mUserName, 'InvalidTubeStickerMotor')
                //             //     );
                //             // }
                //             // else
                //             // {
                //             //     \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                //             // }
                //             $set('tube_sticker_motor_qr', null);

                //             return;
                //         } else {
                //             $set('tube_sticker_motor_error', null);
                //             $set('tube_sticker_motor_qr', $serialNumber);
                //             $set('tube_sticker_motor', '1');
                //         }

                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('tube_sticker_motor_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('tube_sticker_motor_error') ? $get('tube_sticker_motor_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Hidden::make('tube_sticker_pump'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('tube_sticker_pump_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("tube_sticker_pump_qr_$i")
                            ->label("Tube Sticker Pump $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("tube_sticker_pump_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("tube_sticker_pump_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("tube_sticker_pump_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("tube_sticker_pump_error_$i", 'Serial number does not match.');
                                        $set("tube_sticker_pump_qr_$i", null);
                                        return;
                                    }

                                    $set("tube_sticker_pump_qr_$i", $state);
                                    $set('tube_sticker_pump', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("tube_sticker_pump_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("tube_sticker_pump_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("tube_sticker_pump_error_$i", 'Serial number does not match.');
                                    $set("tube_sticker_pump_qr_$i", null);
                                    return;
                                }

                                $set("tube_sticker_pump_error_$i", null);
                                $set("tube_sticker_pump_qr_$i", $serialNumber);
                                $set('tube_sticker_pump', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("tube_sticker_pump_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("tube_sticker_pump_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('tube_sticker_pump_qr')
                //     ->label('Tube Sticker Pump')
                //     ->hidden(fn (callable $get) => ! $get('tube_sticker_pump_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state, $livewire) {

                //         $set('tube_sticker_pump_error', null);

                //         // $mPorder = $get('production_order');

                //         // $mPlantId = $get('plant_id');
                //         // $plant = Plant::find($mPlantId);
                //         // $mPlantName = $plant?->name;

                //         // $mlineId = $get('line_id');

                //         // $mLine = Line::find($mlineId);
                //         // $mLinePart = $mLine?->name;

                //         // $mPorder = $get('production_order');
                //         // $mPlantId = $get('plant_id');
                //         // $mlineId = $get('line_id');
                //         // $mUserName = Filament::auth()->user()?->name ?? 'Unknown';

                //         // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                //         // $mPlantName = $mailData['plant_name'];
                //         // $emails = $mailData['emails'];
                //         // $mUserName = Filament::auth()->user()->name;

                //         if (empty($state)) {
                //             $set('tube_sticker_pump_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('tube_sticker_pump_error', 'Serial number does not match.');
                //                     $set('tube_sticker_pump_qr', null);

                //                     return;
                //                 } else {
                //                     $set('tube_sticker_pump_error', null);
                //                     $set('tube_sticker_pump_qr', $serialNumber);
                //                     $set('tube_sticker_pump', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('tube_sticker_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('tube_sticker_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('tube_sticker_pump_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('tube_sticker_pump_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('tube_sticker_pump_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('tube_sticker_pump_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('tube_sticker_pump_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('tube_sticker_pump_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);
                //         $visibleSerialNumber = $get('serial_number');

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('tube_sticker_pump_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('tube_sticker_pump_error', $serialNumber);

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('tube_sticker_pump_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('tube_sticker_pump_error', 'Serial number does not match.');
                //             $set('tube_sticker_pump_qr', null);
                //             // $user = User::where('name', $mUserName)->first();

                //             // if ($user) {
                //             //     $user->notify(new StatusUpdated($state));
                //             // }

                //             // $currentUser = Filament::auth()->user();

                //             // if ($currentUser) {
                //             // $currentUser->notify(new StatusUpdated($state)); // standard Laravel DB notification

                //             // // refresh Filament bell
                //             //  $livewire->dispatch('refreshFilamentNotifications');
                //             // }

                //             //    Notification::make()
                //             //     ->title('Status Updated')
                //             //     ->body("Serial number scanned: $state")
                //             //     ->danger()
                //             //     ->sendToDatabase($currentUser);

                //             // $user->notify(new StatusUpdated($state));

                //             // Notification::send($user, new StatusUpdated($state));

                //             // dd($user);
                //             // $user->notify(new StatusUpdated($state));
                //             // Inside a Filament page or resource
                //             // $this->notify('success', "Serial number scanned: $state");

                //             // dispatch(new SendInvalidQualityMailJob(
                //             //     $state, $mPorder, $mPlantId, $mlineId, $mUserName, 'InvalidTubeStickerPump'
                //             // ))->afterResponse();

                //             // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                //             // $mPlantName = $mailData['plant_name'];
                //             // $emails = $mailData['emails'];
                //             // $mUserName = Filament::auth()->user()->name;

                //             // if (!empty($emails))
                //             // {
                //             //     //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                //             //     Mail::to($emails)->queue(
                //             //         new InvalidQualityMail($state, $mPorder, $mPlantName,$mLinePart, $mUserName, 'InvalidTubeStickerPumpset')
                //             //     );
                //             // }
                //             // else
                //             // {
                //             //     \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                //             // }

                //             return;
                //         } else {
                //             $set('tube_sticker_pump_error', null);
                //             $set('tube_sticker_pump_qr', $serialNumber);
                //             $set('tube_sticker_pump', '1');
                //         }

                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('tube_sticker_pump_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('tube_sticker_pump_error') ? $get('tube_sticker_pump_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Hidden::make('tube_sticker_pumpset'),

                Forms\Components\Group::make()
                ->schema(function (callable $get) {

                    $fields = [];

                    $count = (int) ($get('tube_sticker_pumpset_qr_count') ?? 0);

                    for ($i = 1; $i <= $count; $i++) {

                        $fields[] = Forms\Components\TextInput::make("tube_sticker_pumpset_qr_$i")
                            ->label("Tube Sticker PumpSet $i")
                            ->reactive()
                            ->required()
                            ->default('')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) use ($i) {

                                $set("tube_sticker_pumpset_error_$i", null);

                                if (empty($state)) {
                                    return;
                                }

                                $visibleSerialNumber = $get('serial_number');

                                if (strpos($state, '|') == false) {

                                    if (strlen($state) < 9) {
                                        $set("tube_sticker_pumpset_error_$i", 'Serial Number must be at least 9 digits.');
                                        return;
                                    }

                                    if (!ctype_alnum($state)) {
                                        $set("tube_sticker_pumpset_error_$i", 'Serial Number must contain alpha-numeric values.');
                                        return;
                                    }

                                    if ($visibleSerialNumber != $state) {
                                        $set("tube_sticker_pumpset_error_$i", 'Serial number does not match.');
                                        $set("tube_sticker_pumpset_qr_$i", null);
                                        return;
                                    }

                                    $set("tube_sticker_pumpset_qr_$i", $state);
                                    $set('tube_sticker_pumpset', '1');
                                    return;
                                }

                                if (!preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                                    $set("tube_sticker_pumpset_error_$i", 'Scan valid QR code.');
                                    return;
                                }

                                $parts = explode('|', $state);

                                $itemCode = trim($parts[0]);

                                $serialNumber = trim($parts[1]);

                                $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber);

                                if ($itemCode != $get('item_id')) {
                                    $set("tube_sticker_pumpset_error_$i", 'Item code does not match.');
                                    return;
                                }

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set("tube_sticker_pumpset_error_$i", 'Serial number does not match.');
                                    $set("tube_sticker_pumpset_qr_$i", null);
                                    return;
                                }

                                $set("tube_sticker_pumpset_error_$i", null);
                                $set("tube_sticker_pumpset_qr_$i", $serialNumber);
                                $set('tube_sticker_pumpset', '1');
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get("tube_sticker_pumpset_error_$i")
                                    ? 'border-red-500'
                                    : '',
                            ])
                            ->hint(fn ($get) => $get("tube_sticker_pumpset_error_$i"))
                            ->hintColor('danger');
                    }

                    return $fields;
                })
                ->columns(2),

                // Forms\Components\TextInput::make('tube_sticker_pumpset_qr')
                //     ->label('Tube Sticker PumpSet')
                //     ->hidden(fn (callable $get) => ! $get('tube_sticker_pumpset_qr_visible'))
                //     ->default('')
                //     ->required()
                //     ->reactive()
                //     ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                //         $set('tube_sticker_pumpset_error', null);

                //         $mPorder = $get('production_order');

                //         $mPlantId = $get('plant_id');
                //         // $plant = Plant::find($mPlantId);
                //         // $plantCodePart4 = $plant?->code;

                //         $mlineId = $get('line_id');

                //         $mLine = Line::find($mlineId);
                //         $mLinePart = $mLine?->name;

                //         if (empty($state)) {
                //             $set('tube_sticker_pumpset_error', null);

                //             return;
                //         }

                //         if (strpos($state, '|') == false) {
                //             if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                //                 $visibleSerialNumber = $get('serial_number');
                //                 $serialNumber = $state;

                //                 if ($visibleSerialNumber != $serialNumber) {
                //                     $set('tube_sticker_pumpset_error', 'Serial number does not match.');
                //                     $set('tube_sticker_pumpset_qr', null);

                //                     return;
                //                 } else {
                //                     $set('tube_sticker_pumpset_error', null);
                //                     $set('tube_sticker_pumpset_qr', $serialNumber);
                //                     $set('tube_sticker_pumpset', '1');

                //                     return;
                //                 }
                //             }

                //             if (strlen($state) < 9) {
                //                 $set('tube_sticker_pumpset_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($state)) {
                //                 $set('tube_sticker_pumpset_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }
                //         } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                //             $splits = explode('|', $state);
                //             $iCode = trim($splits[0]);
                //             $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                //             if (! ctype_alnum($iCode)) {
                //                 $set('tube_sticker_pumpset_error', 'Item code must contain alpha-numeric values.');

                //                 return;
                //             } elseif (strlen($iCode) < 6) {
                //                 $set('tube_sticker_pumpset_error', 'Item code must be at least 6 digits.');

                //                 return;
                //             } elseif (strlen($sNumber) < 9) {
                //                 $set('tube_sticker_pumpset_error', 'Serial Number must be at least 9 digits.');

                //                 return;
                //             } elseif (! ctype_alnum($sNumber)) {
                //                 $set('tube_sticker_pumpset_error', 'Serial Number must contain alpha-numeric values.');

                //                 return;
                //             }

                //             $set('tube_sticker_pumpset_error', 'Scan valid QR code.');

                //             return;
                //         } else {
                //             $set('tube_sticker_pumpset_error', null);
                //         }

                //         // Split state by pipeline "|"
                //         $parts = explode('|', $state);
                //         $itemCode = trim($parts[0]);

                //         $serialNumber = trim($parts[1]);
                //         // $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove
                //         $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove
                //         // Retrieve visible serial numbers
                //         // $visibleSerialNumbers = array_filter([
                //         //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                //         //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                //         //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                //         // ]);
                //         $visibleSerialNumber = $get('serial_number');

                //         // dd($parts);

                //         $expectedItemCode = trim((string) $get('item_id'));

                //         if ($itemCode != $expectedItemCode) {
                //             $set('tube_sticker_pumpset_error', 'Item code does not match.');

                //             return;
                //         }

                //         $set('tube_sticker_pumpset_error', $serialNumber);

                //         //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);
                //         $isMatch = ($visibleSerialNumber == $serialNumber);

                //         if (! $serialNumber || trim($serialNumber) == '') {
                //             $set('tube_sticker_pumpset_error', null);

                //             return;
                //         }

                //         if (! $isMatch) {
                //             $set('tube_sticker_pumpset_error', 'Serial number does not match.');
                //             // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                //             // $mPlantName = $mailData['plant_name'];
                //             // $emails = $mailData['emails'];
                //             // $mUserName = Filament::auth()->user()->name;

                //             // if (!empty($emails))
                //             // {
                //             //     //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                //             //     Mail::to($emails)->send(
                //             //         new InvalidQualityMail($state, $mPorder, $mPlantName,$mLinePart, $mUserName, 'InvalidTubeStickerPumpset')
                //             //     );
                //             // }
                //             // else
                //             // {
                //             //     \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                //             // }
                //             $set('tube_sticker_pumpset_qr', null);

                //             return;
                //         } else {
                //             $set('tube_sticker_pumpset_error', null);
                //             $set('tube_sticker_pumpset_qr', $serialNumber);
                //             $set('tube_sticker_pumpset', '1');
                //         }

                //     })
                //     ->extraAttributes(fn ($get) => [
                //         'class' => $get('tube_sticker_pumpset_error') ? 'border-red-500' : '',
                //     ])
                //     ->hint(fn ($get) => $get('tube_sticker_pumpset_error') ? $get('tube_sticker_pumpset_error') : null)
                //     ->hintColor('danger'),

                Forms\Components\Hidden::make('warranty_card'),

                Forms\Components\TextInput::make('warranty_card_qr')
                    ->label('Warranty Card')
                    ->hidden(fn (callable $get) => ! $get('warranty_card_qr_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $set('warranty_card_error', null);

                        if (empty($state)) {
                            $set('warranty_card_error', null);

                            return;
                        }

                        if (strpos($state, '|') == false) {
                            if (preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $state)) {
                                $visibleSerialNumber = $get('serial_number');
                                $serialNumber = $state;

                                if ($visibleSerialNumber != $serialNumber) {
                                    $set('warranty_card_error', 'Serial number does not match.');
                                    $set('warranty_card_qr', null);

                                    return;
                                } else {
                                    $set('warranty_card_error', null);
                                    $set('warranty_card_qr', $serialNumber);
                                    $set('warranty_card', '1');

                                    return;
                                }
                            }

                            if (strlen($state) < 9) {
                                $set('warranty_card_error', 'Serial Number must be at least 9 digits.');

                                return;
                            } elseif (! ctype_alnum($state)) {
                                $set('warranty_card_error', 'Serial Number must contain alpha-numeric values.');

                                return;
                            }
                        } elseif (strpos($state, '|') == true && ! preg_match('/^([a-zA-Z0-9]{6,})\|([1-9][a-zA-Z0-9]{8,})(?:\/[MmPpCc])?\|?$/', $state)) {
                            $splits = explode('|', $state);
                            $iCode = trim($splits[0]);
                            $sNumber = isset($splits[1]) ? trim($splits[1]) : null;

                            if (! ctype_alnum($iCode)) {
                                $set('warranty_card_error', 'Item code must contain alpha-numeric values.');

                                return;
                            } elseif (strlen($iCode) < 6) {
                                $set('warranty_card_error', 'Item code must be at least 6 digits.');

                                return;
                            } elseif (strlen($sNumber) < 9) {
                                $set('warranty_card_error', 'Serial Number must be at least 9 digits.');

                                return;
                            } elseif (! ctype_alnum($sNumber)) {
                                $set('warranty_card_error', 'Serial Number must contain alpha-numeric values.');

                                return;
                            }

                            $set('warranty_card_error', 'Scan valid QR code.');

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

                        // Split state by pipeline "|"
                        $parts = explode('|', $state);
                        $itemCode = trim($parts[0]);

                        $serialNumber = trim($parts[1]);
                        $serialNumber = preg_replace('/\/[MmPpCc]$/', '', $serialNumber); // Remove

                        // Retrieve visible serial numbers
                        // $visibleSerialNumbers = array_filter([
                        //     $get('serial_number_motor_qr_visible') ? trim((string) $get('serial_number_motor')) : null,
                        //     $get('serial_number_pump_qr_visible') ? trim((string) $get('serial_number_pump')) : null,
                        //     $get('serial_number_pumpset_qr_visible') ? trim((string) $get('serial_number_pumpset')) : null,
                        // ]);

                        $visibleSerialNumber = $get('serial_number');

                        $expectedItemCode = trim((string) $get('item_id'));

                        if ($itemCode != $expectedItemCode) {
                            $set('warranty_card_error', 'Item code does not match.');

                            return;
                        }

                        $set('warranty_card_error', $serialNumber);

                        //  $isMatch = in_array($serialNumber, $visibleSerialNumbers, true);

                        $isMatch = ($visibleSerialNumber == $serialNumber);

                        if (! $serialNumber || trim($serialNumber) == '') {
                            $set('warranty_card_error', null);

                            return;
                        }

                        if (! $isMatch) {
                            $set('warranty_card_error', 'Serial number does not match.');
                            $set('warranty_card_qr', null);

                            return;
                        } else {
                            $set('warranty_card_error', null);
                            $set('warranty_card_qr', $serialNumber);
                            $set('warranty_card', '1');
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('warranty_card_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('warranty_card_error') ? $get('warranty_card_error') : null)
                    ->hintColor('danger'),

                Forms\Components\TextInput::make('part_validation1')
                    ->label('Part Validation 1')
                    ->hidden(fn (callable $get) => ! $get('part_validation1_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $mPorder = $get('production_order');

                        $mPlantId = $get('plant_id');

                        $mlineId = $get('line_id');

                        $plant = Plant::find($mPlantId);
                        $plantCodePart1 = $plant?->code;

                        $mLine = Line::find($mlineId);
                        $mLinePart = $mLine?->name;

                        $stickerMasterId = $get('sticker_master_id');
                        if (! $stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (! $stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation1;
                        $mExpectedValue = $expectedValue ?? null;

                        if ($state == null || trim($state) == '') {
                            $set('part_validation1_error', null);

                            return;
                        }


                        if (strpos($state, '|') !== false) {
                            $state = explode('|', $state)[0];
                            if ($state != $expectedValue){
                                $set('part_validation1_error', 'Invalid input for part validation 1.');
                            }
                            else{
                                $set('part_validation1', $state);
                                $set('part_validation1_error', null);
                            }
                        }
                        if ($state == $expectedValue) {
                            $set('part_validation1_error', null);
                        } else {
                            $set('part_validation1_error', 'Invalid input for part validation 1.');

                            // .Mail

                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];
                            $ccEmails = $mailData['cc_emails'] ?? [];
                            $mUserName = Filament::auth()->user()->name;

                            // if (! empty($emails)) {
                            //     if (is_array($emails)) {
                            //         $emailList = collect($emails)
                            //             ->flatMap(fn ($email) => explode(',', $email))
                            //             ->map(fn ($email) => trim($email))
                            //             ->filter()
                            //             ->toArray();
                            //     } else {
                            //         $emailList = array_map('trim', explode(',', $emails));
                            //     }

                            //     $ccList = [];

                            //     if (!empty($cc_emails)) {
                            //         if (is_array($cc_emails)) {
                            //             $ccList = collect($cc_emails)
                            //                 ->flatMap(fn ($email) => explode(',', $email))
                            //                 ->map(fn ($email) => trim($email))
                            //                 ->filter()
                            //                 ->toArray();
                            //         } else {
                            //             $ccList = collect(explode(',', $cc_emails))
                            //                 ->map(fn ($email) => trim($email))
                            //                 ->filter()
                            //                 ->toArray();
                            //         }
                            //     }

                            //     Mail::to($emailList)
                            //         ->cc($ccList)
                            //         ->send(
                            //         new InvalidQualityMail(
                            //             $state,
                            //             $mPorder,
                            //             $mPlantName,
                            //             $mLinePart,
                            //             $mUserName,
                            //             $mExpectedValue,
                            //             'InvalidPartNumber'
                            //         )
                            //     );
                            // }
                            if (!empty($emails)) {

                                $emailList = collect(is_array($emails) ? $emails : explode(',', $emails))
                                    ->flatMap(fn ($email) => explode(',', $email))
                                    ->map(fn ($email) => trim($email))
                                    ->filter()
                                    ->toArray();

                                $ccList = collect(is_array($ccEmails) ? $ccEmails : explode(',', $ccEmails))
                                    ->flatMap(fn ($email) => explode(',', $email))
                                    ->map(fn ($email) => trim($email))
                                    ->filter()
                                    ->toArray();

                                Mail::to($emailList)
                                    ->cc($ccList)
                                    ->send(
                                        new InvalidQualityMail(
                                            $state,
                                            $mPorder,
                                            $mPlantName,
                                            $mLinePart,
                                            $mUserName,
                                            $mExpectedValue,
                                            'InvalidPartNumber'
                                        )
                                    );
                            }
                            else {
                                \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            }
                            $set('part_validation1', null);

                            $fileName = $expectedValue.'.png'; // or .jpg based on your file
                            $fullPath = storage_path("app/private/uploads/PartValidation/{$fileName}");

                            // dd($fullPath);

                            // // Generate URL through custom route
                            // $imageUrl = route('part.validation.image', [
                            //     'plant' => $plantCodePart1,
                            //     'filename' => $fileName
                            // ]);
                            if (file_exists($fullPath)) {
                                $imageUrl = route('part.validation.image', [
                                    // 'plant' => $plantCodePart1,
                                    'filename' => $fileName,
                                ]);
                            } else {
                                $imageUrl = asset('images/not_found.png');
                            }

                            $set('part_validation1_error_image', $imageUrl);

                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation1_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation1_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation1_error_image'),

                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation1_error') != null)
                    ->statePath('part_validation1_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation2')
                    ->label('Part Validation 2')
                    ->hidden(fn (callable $get) => ! $get('part_validation2_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {

                        $mPorder = $get('production_order');

                        $mPlantId = $get('plant_id');
                        $plant = Plant::find($mPlantId);
                        $plantCodePart2 = $plant?->code;

                        $mlineId = $get('line_id');

                        $mLine = Line::find($mlineId);
                        $mLinePart = $mLine?->name;

                        $stickerMasterId = $get('sticker_master_id');
                        if (! $stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (! $stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation2;
                        $mExpectedValue = $expectedValue ?? null;

                        if ($state == null || trim($state) == '') {
                            $set('part_validation2_error', null);

                            return;
                        }

                        if ($state == $expectedValue) {
                            $set('part_validation2_error', null);
                        } else {
                            $set('part_validation2_error', 'Invalid input for part validation 2.');
                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];
                            $mUserName = Filament::auth()->user()->name;

                            if (! empty($emails)) {
                                // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                                Mail::to($emails)->send(
                                    new InvalidQualityMail($state, $mPorder, $mPlantName, $mLinePart, $mUserName, $mExpectedValue, 'InvalidPartNumber2')
                                );
                            } else {
                                \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            }
                            $set('part_validation2', null);

                            $fileName = $expectedValue.'.png'; // or .jpg based on your file
                            $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart2}/{$fileName}");

                            // if (!file_exists($fullPath)) {
                            //     Notification::make()
                            //         ->title('Image Not Found')
                            //         ->body($fileName)
                            //         ->danger()
                            //         ->send();
                            //     return;
                            // }

                            // Generate URL through custom route
                            $imageUrl = route('part.validation.image', [
                                'plant' => $plantCodePart2,
                                'filename' => $fileName,
                            ]);

                            $set('part_validation2_error_image', $imageUrl);

                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation2_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation2_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation2_error_image')
                    ->default(null)
                    ->dehydrated(false),

                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation2_error') != null)
                    ->statePath('part_validation2_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation3')
                    ->label('Part Validation 3')
                    ->hidden(fn (callable $get) => ! $get('part_validation3_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $stickerMasterId = $get('sticker_master_id');

                        $mPorder = $get('production_order');

                        $mPlantId = $get('plant_id');
                        $plant = Plant::find($mPlantId);
                        $plantCodePart3 = $plant?->code;

                        $mlineId = $get('line_id');

                        $mLine = Line::find($mlineId);
                        $mLinePart = $mLine?->name;

                        if (! $stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (! $stickerMaster) {
                            return;
                        }

                        if ($state == null || trim($state) == '') {
                            $set('part_validation3_error', null);

                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation3;
                        $mExpectedValue = $expectedValue ?? null;

                        if ($state == $expectedValue) {
                            $set('part_validation3_error', null);
                        } else {
                            $set('part_validation3_error', 'Invalid input for part validation 3.');
                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];
                            $mUserName = Filament::auth()->user()->name;

                            if (! empty($emails)) {
                                // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                                Mail::to($emails)->send(
                                    new InvalidQualityMail($state, $mPorder, $mPlantName, $mLinePart, $mUserName, $mExpectedValue, 'InvalidPartNumber3')
                                );
                            } else {
                                \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            }
                            $set('part_validation3', null);
                            $fileName = $expectedValue.'.png'; // or .jpg based on your file
                            // $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart3}/{$fileName}");

                            // if (!file_exists($fullPath)) {
                            //     Notification::make()
                            //         ->title('Image Not Found')
                            //         ->body($fileName)
                            //         ->danger()
                            //         ->send();
                            //     return;
                            // }

                            // Generate URL through custom route
                            $imageUrl = route('part.validation.image', [
                                'plant' => $plantCodePart3,
                                'filename' => $fileName,
                            ]);

                            $set('part_validation2_error_image', $imageUrl);

                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation3_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation3_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation3_error_image')
                    ->default(null)
                    ->dehydrated(false),

                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation3_error') != null)
                    ->statePath('part_validation3_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation4')
                    ->label('Part Validation 4')
                    ->hidden(fn (callable $get) => ! $get('part_validation4_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $stickerMasterId = $get('sticker_master_id');
                        $mPorder = $get('production_order');

                        $mPlantId = $get('plant_id');
                        $plant = Plant::find($mPlantId);
                        $plantCodePart4 = $plant?->code;

                        $mlineId = $get('line_id');

                        $mLine = Line::find($mlineId);
                        $mLinePart = $mLine?->name;

                        if (! $stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (! $stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation4;
                        $mExpectedValue = $expectedValue ?? null;

                        // If input is empty, reset the error
                        if ($state == null || trim($state) == '') {
                            $set('part_validation4_error', null);

                            return;
                        }

                        if ($state == $expectedValue) {
                            $set('part_validation4_error', null);
                        } else {
                            $set('part_validation4_error', 'Invalid input for part validation 4.');
                            $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            $mPlantName = $mailData['plant_name'];
                            $emails = $mailData['emails'];
                            $mUserName = Filament::auth()->user()->name;

                            if (! empty($emails)) {
                                // Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                                Mail::to($emails)->send(
                                    new InvalidQualityMail($state, $mPorder, $mPlantName, $mLinePart, $mUserName, $mExpectedValue, 'InvalidPartNumber4')
                                );
                            } else {
                                \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            }
                            $set('part_validation4', null);
                            $fileName = $expectedValue.'.png'; // or .jpg based on your file
                            $fullPath = storage_path("app/private/uploads/PartValidation/{$plantCodePart4}/{$fileName}");

                            // Generate URL through custom route
                            $imageUrl = route('part.validation.image', [
                                'plant' => $plantCodePart4,
                                'filename' => $fileName,
                            ]);

                            $set('part_validation4_error_image', $imageUrl);

                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation4_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation4_error'))
                    ->hintColor('danger'),

                Forms\Components\Hidden::make('part_validation4_error_image')
                    ->default(null)
                    ->dehydrated(false),

                Forms\Components\View::make('components.part-validation1-error-icon')
                    ->visible(fn ($get) => $get('part_validation4_error') != null)
                    ->statePath('part_validation4_error_image')
                    ->reactive(),

                Forms\Components\TextInput::make('part_validation5')
                    ->label('Part Validation 5')
                    ->hidden(fn (callable $get) => ! $get('part_validation5_visible'))
                    ->default('')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $stickerMasterId = $get('sticker_master_id');

                        $mPorder = $get('production_order');
                        $mPlantId = $get('plant_id');

                        if (! $stickerMasterId) {
                            return;
                        }

                        $stickerMaster = StickerMaster::find($stickerMasterId);
                        if (! $stickerMaster) {
                            return;
                        }

                        $expectedValue = $stickerMaster->part_validation5;

                        // If input is empty, reset the error
                        if ($state == null || trim($state) == '') {
                            $set('part_validation5_error', null);

                            return;
                        }

                        // if ($state == $expectedValue)
                        // {
                        //     $set('part_validation5_error', null);
                        // }
                        // else if (strpos($state, '/') != false) {
                        //     $parts = explode('/', $state);
                        //     if (count($parts) >= 2) {
                        //         $segmentToValidate = $parts[1];
                        //     }
                        //     else
                        //     {
                        //         $segmentToValidate = null;
                        //     }
                        // }
                        // else
                        // {
                        //     $set('part_validation5_error', "Invalid input for part validation 5.");
                        //     $set('part_validation5', null);
                        //     return;
                        // }
                        if ($state == $expectedValue) {
                            $set('part_validation5_error', null);
                        } elseif (strpos($state, '/') != false) {
                            $parts = explode('/', $state);
                            if (count($parts) >= 2) {
                                $segmentToValidate = $parts[1];
                                if ($segmentToValidate == $expectedValue) {
                                    $set('part_validation5_error', null);
                                    $set('part_validation5', $segmentToValidate);
                                } else {
                                    $set('part_validation5_error', 'Invalid input for part validation 5.');
                                    $set('part_validation5', null);

                                    return;
                                }
                            } else {
                                $set('part_validation5_error', 'Invalid input format for part validation 5.');
                                $set('part_validation5', null);

                                return;
                            }
                        } else {
                            $set('part_validation5_error', 'Invalid input for part validation 5.');
                            // $mailData = \App\Filament\Resources\QualityValidationResource::getMailData($mPlantId);

                            // $mPlantName = $mailData['plant_name'];
                            // $emails = $mailData['emails'];

                            // if (!empty($emails))
                            // {
                            //     //Mail::to($emails)->send(new InvalidSerialMail($serNo, $invoiceNumber, $mPlantName, $mInvoiceType));
                            //     Mail::to($emails)->send(
                            //         new InvalidQualityMail($state, $mPorder, $mPlantName, 'InvalidPartNumber5')
                            //     );
                            // }
                            // else
                            // {
                            //     \Log::warning("No recipients found for plant {$mPlantName}, module Serial, rule invalid_serial.");
                            // }
                            $set('part_validation5', null);

                            return;
                        }

                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation5_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation5_error'))
                    ->hintColor('danger'),

                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),

                Forms\Components\View::make('components.production-checklist-wrapper')
                    ->visible(fn ($livewire) => $livewire->showChecklist)
                    ->statePath('checklist')
                    ->viewData(fn ($livewire) => [
                        'existingRecords' => $livewire->existingRecords->toArray(),
                        'data' => $livewire->data,
                        'showChecklist' => $livewire->showChecklist,
                    ]),

            ]);
    }

    public static function getMailData($plantId)
    {
        $globalEmails = AlertMailRule::where('plant', 0)
            ->where('module', 'QualityValidation')
            ->where('rule_name', 'QualityMail')
            ->where(fn ($q) => $q->whereNull('schedule_type')->orWhere('schedule_type', ''))
            // ->get()
            ->pluck('email')
            ->toArray();

        if (! empty($globalEmails)) {
            return [
                'plant_id' => 0,
                'plant_name' => 'All Plants',
                'emails' => $globalEmails,
            ];
        }

        $mPlantName = Plant::where('id', $plantId)->value('name');

        $emails = AlertMailRule::where('plant', $plantId)
            ->where('module', 'QualityValidation')
            ->where('rule_name', 'QualityMail')
            ->where(fn ($q) => $q->whereNull('schedule_type')->orWhere('schedule_type', ''))
            ->get(['email', 'cc_emails']);
            // ->pluck('email')
            // ->toArray();

        return [
            'plant_id' => $plantId,
            'plant_name' => $mPlantName,
            'emails'     => $emails->pluck('email')->filter()->toArray(),
            'cc_emails'  => $emails->pluck('cc_emails')->filter()->toArray(),
            // 'emails' => $emails,
        ];
    }

    public static function table(Table $table): Table
    {
        return $table
            ->query(QualityValidation::query())
            ->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('plant.name')
                    ->label('Plant Name')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line Name')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('production_order')
                    ->label('Production Order')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('stickerMaster.item.code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('stickerMaster.item.description')
                    ->label('Item Description')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('uom')
                    ->label('Unit of Measure')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number_motor')
                    ->label('Serial Number Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number_pump')
                    ->label('Serial Number Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number_pumpset')
                    ->label('Serial Number Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pack_slip_motor')
                    ->label('Pack Slip Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pack_slip_pump')
                    ->label('Pack Slip Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pack_slip_pumpset')
                    ->label('Pack Slip Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name_plate_motor')
                    ->label('Name Plate Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name_plate_pump')
                    ->label('Name Plate Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name_plate_pumpset')
                    ->label('Name Plate Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tube_sticker_motor')
                    ->label('Tube Sticker Motor')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tube_sticker_pump')
                    ->label('Tube Sticker Pump')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('tube_sticker_pumpset')
                    ->label('Tube Sticker Pumpset')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('warranty_card')
                    ->label('Warranty Card')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation1')
                    ->label('Part Validation 1')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation2')
                    ->label('Part Validation 2')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation3')
                    ->label('Part Validation 3')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation4')
                    ->label('Part Validation 4')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('part_validation5')
                    ->label('Part Validation 5')
                    ->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('operator_id')
                    ->label('Created By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])

            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        Select::make('Plant')
                            ->label('Search by Plant Name')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                if ($userHas && strlen($userHas) > 0) {
                                    return Plant::where('id', $userHas)->pluck('name', 'id')->toArray();
                                } else {
                                    return Plant::whereHas('qualityValidations', function ($query) {
                                        $query->whereNotNull('id');
                                    })->orderBy('code')->pluck('name', 'id');
                                }
                                // return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('sticker_master_id', null);
                                $set('sap_msg_status', null);
                                $set('Line', null);
                                $set('operator_id', null);
                            }),
                        Select::make('Line')
                            ->label('Search by Line Name')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return [];
                                }

                                return Line::whereHas('qualityValidations', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('name', 'id');
                                // return Line::where('plant_id', $plantId)->pluck('name', 'id')->toArray();
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('sticker_master_id', null);
                                $set('sap_msg_status', null);
                                $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('sticker_master_id')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $pId = $get('Plant');

                                return Item::whereHas('stickerMasters', function ($query) use ($pId) {
                                    if ($pId) {
                                        $query->where('plant_id', $pId);
                                    }
                                    $query->whereHas('qualityValidations');
                                })->pluck('code', 'id');
                            }),
                        Select::make('sap_msg_status')
                            ->label('Select SAP Message Status')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

                                if (! $plantId) {
                                    return QualityValidation::whereNotNull('sap_msg_status')->select('sap_msg_status')->distinct()->pluck('sap_msg_status', 'sap_msg_status');
                                } else {
                                    return QualityValidation::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'))
                        Select::make('operator_id')
                            ->label('Created By')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                $lineId = $get('Line');
                                if (! $plantId && ! $lineId) {
                                    return QualityValidation::whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                } elseif ($plantId && ! $lineId) {
                                    return QualityValidation::where('plant_id', $plantId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                } else { // if ($plantId && $lineId)
                                    return QualityValidation::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('operator_id')->select('operator_id')->distinct()->pluck('operator_id', 'operator_id');
                                }
                            }),
                        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) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['production_order']) && empty($data['serial_number']) && empty($data['sap_msg_status']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['operator_id']) && empty($data['sticker_master_id'])) {
                            return $query->whereRaw('1 = 0');
                        }

                        if (! empty($data['Plant'])) {
                            $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['Line'])) {
                            $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['sap_msg_status'])) {
                            $query->where('sap_msg_status', $data['sap_msg_status']);
                        }

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

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

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

                        if (! empty($data['sticker_master_id'])) {
                            $stickerMasterIds = StickerMaster::where('item_id', $data['sticker_master_id'])
                                ->pluck('id')
                                ->toArray();

                            if (! empty($stickerMasterIds)) {
                                $query->whereIn('sticker_master_id', $stickerMasterIds);
                            }
                        }

                        // $query->orderBy('created_at', 'asc');
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

                        if (! empty($data['Plant'])) {
                            $indicators[] = 'Plant Name: '.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['Line'])) {
                            $indicators[] = 'Line Name: '.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['sticker_master_id'])) {
                            $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown';
                            $indicators[] = 'Item Code: '.$itemCode;
                        }

                        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(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Quality Validations')
                    ->color('warning')
                    ->importer(QualityValidationImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import quality validation');
                    }),
                ExportAction::make()
                    ->label('Export Quality Validations')
                    ->color('warning')
                    ->exporter(QualityValidationExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export quality validation');
                    }),
            ]);
    }

    // public static function mutateFormDataBeforeCreate(array $data): array
    // {
    //    $user =Filament::auth()->user();
    //    dd($user);
    //    if($user){
    //     $data['operator_id'] = $user->name;
    //    }
    //    // $data['operator_id'] = Filament::auth()->user()->name;
    //     return $data;
    // }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListQualityValidations::route('/'),
            'create' => Pages\CreateQualityValidation::route('/create'),
            'view' => Pages\ViewQualityValidation::route('/{record}'),
            'edit' => Pages\EditQualityValidation::route('/{record}/edit'),
        ];
    }

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