<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PanelBoxValidationResource\Pages;
use App\Filament\Resources\PanelBoxValidationResource\RelationManagers;
use App\Models\PanelBoxValidation;
use App\Models\ProductionCharacteristic;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\StickerMaster;
use App\Models\PanelGrMaster;
use Filament\Notifications\Notification;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Filters\Filter;
use Str;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use App\Filament\Exports\PanelBoxValidationExporter;
use App\Filament\Imports\PanelBoxValidationImporter;
use Filament\Forms\Components\Actions;
use Filament\Forms\Components\Actions\Action;
use Illuminate\Support\Js;

class PanelBoxValidationResource extends Resource
{
    protected static ?string $model = PanelBoxValidation::class;

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

    protected static ?string $navigationGroup = 'Panel Box';

    public $isSubmitted = false;

    public $data = [];

    public bool $showChecklist = false;

    public static function form(Form $form): Form
    {
        return $form
            ->statePath('data')
            ->schema([
                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('inspection_lot_number', 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('inspection_lot_number', 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('serialPanelConfirmed')
                    ->reactive()
                    ->default(false),
                Forms\Components\Hidden::make('sticker_master_id')
                    // ->relationship('stickerMaster', 'id')
                    ->required(),
                Forms\Components\TextInput::make('production_order')
                    ->label('Production Order\Doc No')
                    ->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\TextInput::make('inspection_lot_number')
                    ->label('Inspec Lot No')
                    ->placeholder('Scan the valid Inspec Lot No')
                    ->minLength(7)
                    ->maxLength(14)
                    ->reactive()
                    ->readOnly(fn (callable $get) => $get('item_id'))
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if (! is_numeric($get('inspection_lot_number'))) {
                            $set('inspecOrdError', 'Must be a numeric value.');
                            $set('item_id', null);
                            $set('sticker_master_id', null);
                            $set('uom', null);
                            $set('serial_number', null);
                        } else {
                            $set('inspecOrdError', null);
                            $set('inspection_lot_number', $state);
                            $set('inspection', $state);
                        }
                    })
                    ->default(fn ($get) => $get('inspection') ?? session('last_selected_inspection'))
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('inspecOrdError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('inspecOrdError') ? $get('inspecOrdError') : null)
                    ->hintColor('danger')
                    ->required(),
                Forms\Components\Hidden::make('inspection')
                    ->default(fn () => session('last_selected_inspection'))
                    ->afterStateHydrated(function ($state, $set) {
                        if (! $state && request()->has('inspection_lot_number')) {
                            $set('inspection_lot_number', request()->get('inspection_lot_number'));
                        }
                    }),
                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) {

                        $state = trim($state);
                        $pId = $get('line_id');
                        $plantId = $get('plant_id');
                        $plaCode = Plant::find($plantId)?->code;
                        $inspecLotNo = $get('inspection_lot_number');
                        $set('part_validation_type', null);
                        $set('show_validation_image', false);
                        $set('validation1_image_url', null);
                        $set('serialPanelConfirmed', false);


                        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', 'pack_slip_motor_qr', 'name_plate_motor_qr', 'tube_sticker_motor_qr', 'warranty_card_qr',
                        ];

                        $set('serial_number', null);

                        $serialnumber = ['serial_number_motor_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('serial_exists', false);
                            $set('validationError', null);
                            return;
                        }

                        // Check if QR format contains '|'

                        if ($state && str_contains($state, '|'))
                        {
                            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)) {
                                $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;
                                }

                                $existInMasterPo = PanelGrMaster::where('document_number', $pOrder)->where('plant_id', $plantId)->first();

                                if(!$existInMasterPo){
                                    Notification::make()
                                        ->title('Panel GR Record')
                                        ->body("Production Order (Or) Doc No'{$pOrder}' not found against plant code '{$plaCode}' in Panel Gr master.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                    return;
                                }

                                $iId = Item::where('code', $iCode)->where('plant_id', $plantId)->first();

                                if(!$iId){
                                    Notification::make()
                                        ->title('Item not found')
                                        ->body("Item code'{$iCode}' not found against plant code '{$plaCode}' in item master.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                    return;
                                }

                                $existInMaster = PanelGrMaster::where('document_number', $pOrder)->where('item_id', $iId->id)->where('plant_id', $plantId)->first();

                                if(!$existInMaster){
                                    Notification::make()
                                        ->title('Panel GR Record Not Found')
                                        ->body("No Panel GR record found for Production Order (Or) Doc No'{$pOrder}' and for Item '{$iCode}'.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                    return;
                                }
                                else if($existInMaster->supplier_number == '' || $existInMaster->supplier_number == null){
                                    Notification::make()
                                        ->title('Panel GR Found')
                                        ->body("Supplier Number cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$iCode}'.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                    return;
                                }
                                // else if($existInMaster->supplier_number != $supplier){
                                //     Notification::make()
                                //         ->title('Panel GR Found')
                                //         ->body("Supplier code not match for Production Order (Or) Doc No'{$pOrder}' and Item '{$iCode}'.")
                                //         ->danger()
                                //         ->send();
                                //     $set('item_id', null);
                                //     return;
                                // }
                                else if($existInMaster->quantity == '' || $existInMaster->quantity == null){
                                    Notification::make()
                                        ->title('Panel GR Found')
                                        ->body("Quantity cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$iCode}'.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                    return;
                                }
                                else if($existInMaster->invoice_number == '' || $existInMaster->invoice_number == null){
                                    Notification::make()
                                        ->title('Panel GR Found')
                                        ->body("Invoice Number cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$iCode}'.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                    return;
                                }

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

                                if(!$sticker){
                                    Notification::make()
                                        ->title('Unknown Item Code')
                                        ->body("Item code not found '{$iId->code}' in sticker master.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                }

                                $existQuanInPanel = PanelBoxValidation::where('plant_id', $plantId)->where('production_order', $pOrder)->where('sticker_master_id', $sticker->id)->count();

                                if ($existQuanInPanel >= (int) $existInMaster->quantity) {
                                    Notification::make()
                                        ->title('Quantity Completed')
                                        ->body("Panel box quantity '{$existQuanInPanel}' exceeds the available quantity '{$existInMaster->quantity}' in Panel GR Master for Production Order '{$pOrder}' and Item '{$iCode}'.")
                                        ->danger()
                                        ->send();
                                    $set('item_id', null);
                                    return;
                                }
                            } else {
                                $set('validationError', null);
                            }
                        }
                        if (str_contains($state, '|')) {

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

                            if (count($parts) != 2) {
                                Notification::make()
                                    ->title('Invalid QR Format')
                                    ->body('Expected format: ItemCode|SerialNumber')
                                    ->danger()
                                    ->send();

                                return;
                            }

                            $itemCode = $parts[0];
                            $serialNumber = $parts[1];

                            if($serialNumber == '' || $serialNumber == null){
                                Notification::make()
                                    ->title('Unknown Serial number')
                                    ->body("Serial number can't be empty!")
                                    ->danger()
                                    ->send();

                                $set('item_id', null);
                                return;
                            }
                            elseif (! ctype_alnum($serialNumber)) {
                                $set('validationError', 'Serial Number should contain alpha-numeric values.');
                                $set('item_id', null);
                                return;
                            }

                            $existInMasterPo = PanelGrMaster::where('document_number', $pOrder)->where('plant_id', $plantId)->first();

                            if(!$existInMasterPo){
                                Notification::make()
                                    ->title('Panel GR Record')
                                    ->body("Production Order (Or) Doc No'{$pOrder}' not found against plant code '{$plaCode}' in Panel Gr master.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

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

                            if(!$iId){
                                Notification::make()
                                    ->title('Item not found')
                                    ->body("Item code'{$itemCode}' not found against plant code '{$plaCode}' in item master.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

                            $existInMaster = PanelGrMaster::where('document_number', $pOrder)->where('item_id', $iId->id)->where('plant_id', $plantId)->first();

                            if(!$existInMaster){
                                Notification::make()
                                    ->title('Panel GR Record Not Found')
                                    ->body("No Panel GR record found for Production Order (Or) Doc No'{$pOrder}' and for Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }
                            else if($existInMaster->supplier_number == '' || $existInMaster->supplier_number == null){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Supplier Number cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }
                            // else if($existInMaster->supplier_number != $supplier){
                            //     Notification::make()
                            //         ->title('Panel GR Found')
                            //         ->body("Supplier code not match for Production Order (Or) Doc No'{$pOrder}' and Item '{$iCode}'.")
                            //         ->danger()
                            //         ->send();
                            //     $set('item_id', null);
                            //     return;
                            // }
                            else if($existInMaster->quantity == '' || $existInMaster->quantity == null){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Quantity cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }
                            else if($existInMaster->invoice_number == '' || $existInMaster->invoice_number == null){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Invoice Number cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

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

                            if(!$sticker){
                                Notification::make()
                                    ->title('Unknown Item Code')
                                    ->body("Item code not found '{$iId->code}' in sticker master.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                            }

                            $existQuanInPanel = PanelBoxValidation::where('plant_id', $plantId)->where('production_order', $pOrder)->where('sticker_master_id', $sticker->id)->count();

                            if ($existQuanInPanel >= (int) $existInMaster->quantity) {
                                Notification::make()
                                    ->title('Quantity Completed')
                                    ->body("Panel box quantity '{$existQuanInPanel}' exceeds the available quantity '{$existInMaster->quantity}' in Panel GR Master for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

                        }
                        elseif (str_contains($state, '/'))
                        {
                            $parts = explode('/', $state);

                            if (count($parts) < 3) {

                                Notification::make()
                                    ->title('Invalid QR Format')
                                    ->body('Expected format: plantcode/itemcode/yearmm/serialnumber (Or) plantcode/panelboxcode/serialnumber')
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }

                            $supplier = $parts[0];
                            $panelBoxCode = $parts[1];
                            $panelBoxSerialNo = implode('/', array_slice($parts, 2));

                            $itemCode = $panelBoxCode;
                            $serialNumber = $panelBoxSerialNo;

                            $existInMasterPo = PanelGrMaster::where('document_number', $pOrder)->where('plant_id', $plantId)->first();

                            if(!$existInMasterPo){
                                Notification::make()
                                    ->title('Panel GR Record')
                                    ->body("Production Order (Or) Doc No'{$pOrder}' not found against plant code '{$plaCode}' in Panel Gr master.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }

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

                            if(!$iId){
                                Notification::make()
                                    ->title('Item not found')
                                    ->body("Item code'{$itemCode}' not found against plant code '{$plaCode}' in item master.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }

                            $existInMaster = PanelGrMaster::where('document_number', $pOrder)->where('inspection_lot_number', $inspecLotNo)->where('item_id', $iId->id)->where('plant_id', $plantId)->first();

                            if(!$existInMaster){
                                Notification::make()
                                    ->title('Panel GR Record Not Found')
                                    ->body("No Panel GR record found for Production Order (Or) Doc No'{$pOrder}' , inspection lot number '{$inspecLotNo}' and for Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }
                            else if($existInMaster->supplier_number == '' || $existInMaster->supplier_number == null){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Supplier Number cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }
                            else if($existInMaster->supplier_number != $supplier){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Supplier code not match for Production Order (Or) Doc No'{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }
                            else if($existInMaster->inspection_lot_number != $inspecLotNo){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Inspection Lot Number code not match for Production Order (Or) Doc No'{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }
                            else if($existInMaster->quantity == '' || $existInMaster->quantity == null){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Quantity cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }
                            else if($existInMaster->invoice_number == '' || $existInMaster->invoice_number == null){
                                Notification::make()
                                    ->title('Panel GR Found')
                                    ->body("Invoice Number cannot be empty Panel GR record found for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }

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

                            if(!$sticker){
                                Notification::make()
                                    ->title('Unknown Item Code')
                                    ->body("Item code not found '{$iId->code}' in sticker master.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }

                            $existQuanInPanel = PanelBoxValidation::where('plant_id', $plantId)->where('production_order', $pOrder)->where('inspection_lot_number', $inspecLotNo)->where('sticker_master_id', $sticker->id)->count();

                            if ($existQuanInPanel >= (int) $existInMaster->quantity) {
                                Notification::make()
                                    ->title('Quantity Completed')
                                    ->body("Panel box quantity '{$existQuanInPanel}' exceeds the available quantity '{$existInMaster->quantity}' in Panel GR Master for Production Order '{$pOrder}' and Item '{$itemCode}'.")
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                $set('serial_exists', false);
                                return;
                            }

                            $set('panel_box_supplier', $supplier);
                            $set('panel_box_serial_number', $panelBoxSerialNo);
                            $set('panel_box_code', $panelBoxCode);
                        }
                        else {

                            Notification::make()
                                ->title('Invalid QR Format')
                                ->body('QR must be in either ItemCode|SerialNumber or PlantCode/ItemCode/YearMM/SerialNumber format.')
                                ->danger()
                                ->send();
                            $set('item_id', null);
                            $set('serial_exists', false);
                            $set('validationError', null);
                            return;
                        }

                        if (strlen($itemCode) < 6) {
                            $set('validationError', 'Item code must be at least 6 digits.');
                            $set('part_validation_type', null);
                            $set('serial_exists', false);
                            $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('serial_exists', false);
                            $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);
                        }

                        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);
                            $set('serial_exists', false);

                            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);
                                $set('serial_exists', false);

                                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);
                                $set('serial_exists', false);

                                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 = PanelBoxValidation::where('serial_number', $serialNumber)->where('plant_id', $plantId)->first();

                        if ($serialExists) {
                            $set('serial_exists', true);
                        } else {
                            $set('serial_exists', false);
                        }

                        // if ($serialExists && ! $get('id')) {
                        //     $set('validationError', 'Serial number already exists in panel box validation.');
                        //     $set('sticker_master_id', null);
                        //     $set('uom', null);
                        //     $set('serial_number', null);

                        //     return;
                        // }

                        $set('validationError', null);

                        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';
                        }

                        $set('part_validation_type_options', $options);

                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('validationError') ? 'border-red-500' : '',
                        'id' => 'item_id',
                        'onkeydown' => "
                            if (event.key === 'Enter') {

                                const serialFields = [
                                    'serial_number_motor_qr', 'serial_number_pump_qr', 'pack_slip_motor_qr',
                                    'name_plate_motor_qr', 'tube_sticker_motor_qr', 'warranty_card_qr'
                                ];
                                const partValidationColumns = [
                                    'part_validation1', 'part_validation2', 'part_validation3',
                                    'part_validation4', 'part_validation5'
                                ];

                                const allFields = [...serialFields.map(f => f + '_visible'), ...partValidationColumns.map(f => f + '_visible')];

                                const anyVisible = allFields.some(key => {
                                    const el = document.querySelector('[wire\\\\:model*=\"' + key + '\"]');
                                    return el && (el.value === '1' || el.value === 'true' || el.checked);
                                });

                                if (anyVisible) {
                                    event.preventDefault();
                                    event.stopPropagation();
                                    event.stopImmediatePropagation();
                                    return false;
                                }
                            }
                        ",
                    ])
                    ->hint(fn ($get) => $get('validationError') ? $get('validationError') : null)
                    ->hintColor('danger'),
                Forms\Components\Hidden::make('serial_exists')
                    // ->default(false)
                    ->live()
                    ->dehydrated()
                    ->id('serial_exists'),

                Forms\Components\Actions::make([
                    Action::make('rework')
                        ->label('Yes, Rework')
                        ->color('warning')
                        ->requiresConfirmation()
                        ->modalHeading('Confirm Rework')
                        ->modalDescription('Have you reworked this serial number?')
                        ->modalSubmitActionLabel('Yes, Continue')
                        ->visible(fn ($get) => $get('serial_exists') == true)
                        ->action(function ($get, $livewire) {

                            $serialNumber = $get('serial_number');
                            $plantId = $get('plant_id');
                            $pOrder = $get('production_order');
                            $inspecLotNo = $get('inspection_lot_number');

                            $alreadyExists = PanelBoxValidation::where('serial_number', $serialNumber)
                                ->where('plant_id', $plantId)
                                ->where('production_order', $pOrder)
                                ->where('inspection_lot_number', $inspecLotNo)
                                ->first();

                            if ($alreadyExists) {
                                Notification::make()
                                    ->title('Duplicate Found')
                                    ->body(
                                        'This document number and inspection lot number have already been used for this serial number. Please provide a new document number and inspection lot number for rework...'
                                    )
                                    ->danger()
                                    ->send();

                                $livewire->showChecklist = false;

                                return;
                            }
                            $data = $get();

                            $hasCharacteristics = $livewire->checkIfHasCharacteristics($data);

                            \Log::info('CHARACTERISTICS RESULT', [
                                'hasCharacteristics' => $hasCharacteristics,
                            ]);

                            if ($hasCharacteristics) {

                                \Log::info('SETTING SHOW CHECKLIST TRUE');

                                $livewire->showChecklist = true;
                                $livewire->dispatch('close-modal');
                                return;
                            }
                            else{
                                Notification::make()
                                    ->title('Not Found Characteristics')
                                    ->body('item characteristics not found')
                                    ->danger()
                                    ->send();
                                $livewire->showChecklist = false;
                                return;
                            }
                            // else
                            // {
                            //     // $livewire->showChecklist = true;
                            //     // $data = $livewire->data;
                            //     $data = $get();

                            //     if ($livewire->checkIfHasCharacteristics($data)) {

                            //         $livewire->showChecklist = true;
                            //         $livewire->dispatch('close-modal');
                            //         return;
                            //     }
                            // }
                        }),
                    ]),
                Forms\Components\Hidden::make('part_validation_type_options')
                    ->default([])
                    ->reactive()
                    ->dehydrated(false),
                Forms\Components\Hidden::make('show_validation_image')
                    ->reactive()
                    ->default(false),
                Forms\Components\Hidden::make('validation1_image_url')
                    ->reactive(),
                Forms\Components\Hidden::make('serial_number')
                    ->reactive(),
                Forms\Components\Hidden::make('panel_box_supplier')
                    ->reactive(),
                Forms\Components\Hidden::make('panel_box_serial_number')
                    ->reactive(),
                Forms\Components\Hidden::make('panel_box_code')
                    ->reactive(),
                Forms\Components\TextInput::make('serial_number_motor_qr')
                    ->label('Serial Number')
                    ->reactive()
                    ->readOnly(fn (callable $get) => !$get('id'))
                    ->hidden(fn (callable $get) => !$get('serial_number_motor_qr_visible'))  // Controls visibility
                    ->default(''),
                Forms\Components\Hidden::make('serial_number_panel')
                    ->reactive(),
                Forms\Components\TextInput::make('serial_number_panel_qr')
                    ->label('Serial Number Panel')
                    ->hidden(fn (callable $get) => !$get('serial_number_pump_qr_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if (!$state || trim($state) == '') {
                            $set('serialPanelError', null);
                            return;
                        }

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

                        if (count($parts) < 3) {

                            Notification::make()
                                ->title('Invalid QR Format')
                                ->body('Expected format: plantcode/itemcode/yearmm/serialnumber (Or) plantcode/panelboxcode/serialnumber')
                                ->danger()
                                ->send();
                            $set('item_id', null);
                            return;
                        }

                        $extracted = trim(end($parts));

                        $expected = $get('serial_number');

                        if ($extracted != $expected) {
                            $set('serialPanelError', 'Serial number panel does not match.');
                            $set('serial_number_panel_qr', null);
                            return;
                        }
                        else{

                            $set('serialPanelError', null);
                            $set('serial_number_panel_qr', $extracted);
                            $set('serial_number_panel', '1');

                            $panelParts = explode('/', $state);

                            if (count($panelParts) < 3) {

                                Notification::make()
                                    ->title('Invalid QR Format')
                                    ->body('Expected format: plantcode/itemcode/yearmm/serialnumber (Or) plantcode/panelboxcode/serialnumber')
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

                            $supplier = $panelParts[0];
                            $panelBoxCode = $panelParts[1];
                            $panelBoxSerialNo = implode('/', array_slice($panelParts, 2));

                            $set('panel_box_supplier', $supplier);
                            $set('panel_box_serial_number', $panelBoxSerialNo);
                            $set('panel_box_code', $panelBoxCode);
                            return;
                        }
                    })
                    ->hint(fn ($get) => $get('serialPanelError') ?? null)
                    ->hintColor('danger')
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('serialPanelError') ? 'border-red-500' : '',
                    ]),
                Forms\Components\Hidden::make('pack_slip_panel')
                    ->reactive(),
                Forms\Components\TextInput::make('pack_slip_panel_qr')
                    ->label('Pack Slip Panel')
                    ->hidden(fn (callable $get) => !$get('pack_slip_motor_qr_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if (!$state || trim($state) == '') {
                            $set('packSlipPanelError', null);
                            return;
                        }

                        if (!preg_match('/^\d+\/\d+\/\d+\/\d+$/', $state)) {
                            Notification::make()
                                ->title('Invalid QR Format')
                                ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                ->danger()
                                ->send();
                            $set('pack_slip_panel_qr', null);
                            return;
                        }

                        $parts = explode('/', $state);
                        $extracted = trim(end($parts));

                        if ($extracted == '') {
                            $set('packSlipPanelError', "SerialNumber can't be empty!");
                            $set('pack_slip_panel_qr', null);
                            return;
                        }

                        $expected = $get('serial_number');

                        if ($extracted != $expected) {
                            $set('packSlipPanelError', 'Pack Slip Panel serial does not match.');
                            $set('pack_slip_panel', null);
                            return;
                        }
                        else{
                            $set('packSlipPanelError', null);
                            $set('pack_slip_panel_qr', $extracted);
                            $set('pack_slip_panel', '1');
                            $panelParts = array_map('trim', explode('/', $state));

                            if (count($panelParts) != 4) {

                                Notification::make()
                                    ->title('Invalid QR Format')
                                    ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

                            $supplier = $panelParts[0];
                            $panelBoxCode = $panelParts[1];
                            $yearMonth = $panelParts[2];
                            $serialNumber = $panelParts[3];
                            $panelBoxSerialNo = $yearMonth . $serialNumber;

                            $set('panel_box_supplier', $supplier);
                            $set('panel_box_serial_number', $panelBoxSerialNo);
                            $set('panel_box_code', $panelBoxCode);
                            return;
                        }
                    })
                    ->hint(fn ($get) => $get('packSlipPanelError') ?? null)
                    ->hintColor('danger')
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('packSlipPanelError') ? 'border-red-500' : '',
                    ]),
                Forms\Components\Hidden::make('name_plate_panel')
                    ->label('Name Plate Panel')
                    ->reactive(),
                Forms\Components\TextInput::make('name_plate_panel_qr')
                    ->label('Name Plate Panel')
                    ->hidden(fn (callable $get) => !$get('name_plate_motor_qr_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if (!$state || trim($state) == '') {
                            $set('namePlatePanelError', null);
                            return;
                        }

                        if (!preg_match('/^\d+\/\d+\/\d+\/\d+$/', $state)) {
                            Notification::make()
                                ->title('Invalid QR Format')
                                ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                ->danger()
                                ->send();
                            $set('serial_number_panel_qr', null);
                            return;
                        }

                        $parts = explode('/', $state);
                        $extracted = trim(end($parts));

                        if ($extracted == '') {
                            $set('namePlatePanelError', "SerialNumber cant't be empty!");
                            $set('name_plate_panel_qr', null);
                            return;
                        }

                        $expected = $get('serial_number');

                        if ($extracted != $expected) {
                            $set('namePlatePanelError', 'Name Plate Panel serial does not match.');
                            $set('name_plate_panel', null);
                            return;
                        }
                        else{
                            $set('namePlatePanelError', null);
                            $set('name_plate_panel_qr', $extracted);
                            $set('name_plate_panel', '1');
                            $panelParts = array_map('trim', explode('/', $state));

                            if (count($panelParts) != 4) {

                                Notification::make()
                                    ->title('Invalid QR Format')
                                    ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

                            $supplier = $panelParts[0];
                            $panelBoxCode = $panelParts[1];
                            $yearMonth = $panelParts[2];
                            $serialNumber = $panelParts[3];
                            $panelBoxSerialNo = $yearMonth . $serialNumber;

                            $set('panel_box_supplier', $supplier);
                            $set('panel_box_serial_number', $panelBoxSerialNo);
                            $set('panel_box_code', $panelBoxCode);
                            return;
                        }
                    })
                    ->hint(fn ($get) => $get('namePlatePanelError') ?? null)
                    ->hintColor('danger')
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('namePlatePanelError') ? 'border-red-500' : '',
                    ]),
                Forms\Components\Hidden::make('tube_sticker_panel')
                    ->label('Tube Sticker Panel')
                    ->reactive(),
                Forms\Components\TextInput::make('tube_sticker_panel_qr')
                    ->label('Tube Sticker Panel')
                    ->hidden(fn (callable $get) => !$get('tube_sticker_motor_qr_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if (!$state || trim($state) == '') {
                            $set('tubeStickerPanelError', null);
                            return;
                        }

                        if (!preg_match('/^\d+\/\d+\/\d+\/\d+$/', $state)) {
                            Notification::make()
                                ->title('Invalid QR Format')
                                ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                ->danger()
                                ->send();
                            $set('serial_number_panel_qr', null);
                            return;
                        }

                        $parts = explode('/', $state);
                        $extracted = trim(end($parts));

                        if ($extracted == '') {
                            $set('tubeStickerPanelError', "SerialNumber can't be empty!");
                            $set('tube_sticker_panel_qr', null);
                            return;
                        }

                        $expected = $get('serial_number');

                        if ($extracted != $expected) {
                            $set('tubeStickerPanelError', 'Tube Sticker Panel serial does not match.');
                            $set('tube_sticker_panel_qr', null);
                            return;
                        }
                        else{
                            $set('tubeStickerPanelError', null);
                            $set('tube_sticker_panel_qr', $extracted);
                            $set('tube_sticker_panel', '1');
                            $panelParts = array_map('trim', explode('/', $state));

                            if (count($panelParts) != 4) {

                                Notification::make()
                                    ->title('Invalid QR Format')
                                    ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

                            $supplier = $panelParts[0];
                            $panelBoxCode = $panelParts[1];
                            $yearMonth = $panelParts[2];
                            $serialNumber = $panelParts[3];
                            $panelBoxSerialNo = $yearMonth . $serialNumber;

                            $set('panel_box_supplier', $supplier);
                            $set('panel_box_serial_number', $panelBoxSerialNo);
                            $set('panel_box_code', $panelBoxCode);
                            return;
                        }
                    })
                    ->hint(fn ($get ) => $get('tubeStickerPanelError') ?? null)
                    ->hintColor('danger')
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('tubeStickerPanelError') ? 'border-red-500' : '',
                    ]),

                Forms\Components\Hidden::make('warranty_card_panel')
                    ->label('Warranty Card')
                    ->reactive(),
                Forms\Components\TextInput::make('warranty_card_qr')
                    ->label('Warranty Card Panel')
                    ->hidden(fn (callable $get) => !$get('warranty_card_qr_visible'))
                    ->default('')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        if (!$state || trim($state) == '') {
                            $set('warrantyCardPanelError', null);
                            return;
                        }

                        if (!preg_match('/^\d+\/\d+\/\d+\/\d+$/', $state)) {
                            Notification::make()
                                ->title('Invalid QR Format')
                                ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                ->danger()
                                ->send();
                            $set('serial_number_panel_qr', null);
                            return;
                        }

                        $parts = explode('/', $state);
                        $extracted = trim(end($parts));

                        if ($extracted == '') {
                            $set('warrantyCardPanelError', "SerialNumber can't be empty!");
                            $set('warranty_card_qr', null);
                            return;
                        }

                        $expected = $get('serial_number');

                        if ($extracted != $expected) {
                            $set('warrantyCardPanelError', 'Warranty Card Panel serial does not match.');
                            $set('warranty_card_qr', null);
                            return;
                        }
                        else{
                            $set('warrantyCardPanelError', null);
                            $set('warranty_card_qr', $extracted);
                            $set('warranty_card_panel', '1');
                            $panelParts = array_map('trim', explode('/', $state));

                            if (count($panelParts) != 4) {

                                Notification::make()
                                    ->title('Invalid QR Format')
                                    ->body('Expected format: plantcode/itemcode/yearmm/serialnumber')
                                    ->danger()
                                    ->send();
                                $set('item_id', null);
                                return;
                            }

                            $supplier = $panelParts[0];
                            $panelBoxCode = $panelParts[1];
                            $yearMonth = $panelParts[2];
                            $serialNumber = $panelParts[3];
                            $panelBoxSerialNo = $yearMonth . $serialNumber;

                            $set('panel_box_supplier', $supplier);
                            $set('panel_box_serial_number', $panelBoxSerialNo);
                            $set('panel_box_code', $panelBoxCode);
                            return;
                        }
                    })
                    ->hint(fn ($get) => $get('warrantyCardPanelError') ?? null)
                    ->hintColor('danger')
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('warrantyCardPanelError') ? 'border-red-500' : '',
                    ]),

                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.');
                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation1_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation1_error'))
                    ->hintColor('danger'),

                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.');

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

                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.');

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

                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;

                        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.');
                            return;
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('part_validation4_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('part_validation4_error'))
                    ->hintColor('danger'),

                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');

                        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);
                        } 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.');
                            $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\Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('updated_by')
                    ->label('Updated By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\View::make('components.panel-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 table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->alignCenter()
                    ->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')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('stickerMaster.item.code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('production_order')
                    ->label('Production Order/Doc No')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('inspection_lot_number')
                    ->label('Inspection Lot No')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number_panel')
                    ->label('Serial Number Panel')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->serial_number_panel == 1),
                Tables\Columns\TextColumn::make('pack_slip_panel')
                    ->label('Pack Slip Panel')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->pack_slip_panel == 1),
                Tables\Columns\TextColumn::make('name_plate_panel')
                    ->label('Name Plate Panel')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->name_plate_panel == 1),
                Tables\Columns\TextColumn::make('tube_sticker_panel')
                    ->label('Tube Sticker Panel')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->tube_sticker_panel == 1),
                Tables\Columns\TextColumn::make('warranty_card_panel')
                    ->label('Warranty Card Panel')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->warranty_card_panel == 1),
                Tables\Columns\TextColumn::make('part_validation1')
                    ->label('Part Validation 1')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->part_validation1 != null),
                Tables\Columns\TextColumn::make('part_validation2')
                    ->label('Part Validation 2')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->part_validation2 != null),
                Tables\Columns\TextColumn::make('part_validation3')
                    ->label('Part Validation 3')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->part_validation3 != null),
                Tables\Columns\TextColumn::make('part_validation4')
                    ->label('Part Validation 4')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->part_validation4 != null),
                Tables\Columns\TextColumn::make('part_validation5')
                    ->label('Part Validation 5')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->visible(fn ($record) => $record?->stickerMaster?->part_validation5 != null),
                Tables\Columns\TextColumn::make('panel_box_supplier')
                    ->label('Panel Box Supplier')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('panel_box_serial_number')
                    ->label('Panel Box Serial Number')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('panel_box_code')
                    ->label('Panel Box Code')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('rework_count')
                    ->label('Rework Count')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->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('panelBoxValidations', 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('Line', null);
                                $set('Item', null);
                                $set('Machine', null);
                            }),
                        Select::make('Line')
                            ->label('Search by Line Name')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

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

                                return Line::whereHas('panelBoxValidations', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('name', 'id');
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Item', null);
                            }),
                        Select::make('sticker_master_id')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $pId = $get('Plant');

                                // if (empty($pId)) {
                                //     return [];
                                // }
                                return Item::whereHas('stickerMasters', function ($query) use ($pId) {
                                    if ($pId) {
                                        $query->where('plant_id', $pId);
                                    }
                                    $query->whereHas('panelBoxValidations');
                                })->pluck('code', 'id');
                            }),
                        TextInput::make('production_order')
                            ->label('Production Order / Doc No')
                            ->reactive()
                            ->placeholder('Enter Production Order (or) Doc No')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('serial_number', null);
                            }),
                        TextInput::make('serial_number')
                            ->label('Serial Number')
                            ->reactive()
                            ->placeholder('Enter Serial Number'),
                        TextInput::make('inspection_lot_number')
                            ->label('Inspection Lot Number')
                            ->reactive()
                            ->placeholder('Enter Inspection Lot Number'),
                        TextInput::make('panel_box_code')
                            ->label('Panel Box Code')
                            ->reactive()
                            ->placeholder('Enter Panel Box Code'),
                        Select::make('rework_count')
                            ->label('Rework')
                            ->options([
                                1 => 'Yes',
                                0 => 'No',
                            ])
                            ->reactive(),
                        DateTimePicker::make(name: 'created_from')
                            ->label('Created From')
                            ->placeholder('Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('created_to')
                            ->label('Created To')
                            ->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['Line']) && empty($data['Item']) && empty($data['production_order']) && empty($data['serial_number']) && empty($data['inspection_lot_number']) && empty($data['panel_box_code']) && empty($data['rework_count']) && empty($data['created_from']) && empty($data['created_to'])) {
                            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['sticker_master_id'])) {
                            $stickerMasterIds = StickerMaster::where('item_id', $data['sticker_master_id'])
                                ->pluck('id')
                                ->toArray();

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

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

                        if (Str::length($data['serial_number']) > 0) {
                            $query->where('serial_number', 'like', '%'.$data['serial_number'].'%');
                        }

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

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

                        if (! empty($data['rework_count'])) {
                            if ($data['rework_count'] == 1) {
                                $query->where('rework_count', '>', 0);
                            }
                            else if ($data['rework_count'] == 0) {
                                $query->where('rework_count', '=', '0');
                            }
                        }

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

                        if (! empty($data['created_to'])) {
                            $query->where('created_at', '<=', $data['created_to']);
                        }
                    })
                    ->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 Name: Choose plant to filter records.';
                            }
                        }

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

                        if (! empty($data['sticker_master_id'])) {
                            $itemCode = Item::find($data['sticker_master_id'])->code ?? 'Unknown';
                            $indicators[] = 'Item Code: '.$itemCode;
                        }

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

                        if (Str::length($data['serial_number']) > 0) {
                            $indicators[] = 'Serial Number: '.$data['serial_number'];
                        }

                        if (! empty($data['inspection_lot_number'])) {
                            $indicators[] = 'Inspection Lot No: '.$data['inspection_lot_number'];
                        }

                        if (! empty($data['panel_box_code'])) {
                            $indicators[] = 'Panel Box Code: '.$data['panel_box_code'];
                        }

                        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 Panel Box Validation')
                    ->color('warning')
                    ->importer(PanelBoxValidationImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import panel box validation');
                    }),
                ExportAction::make()
                    ->label('Export Panel Box Validation')
                    ->color('warning')
                    ->exporter(PanelBoxValidationExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export panel box validation');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPanelBoxValidations::route('/'),
            'create' => Pages\CreatePanelBoxValidation::route('/create'),
            'view' => Pages\ViewPanelBoxValidation::route('/{record}'),
            'edit' => Pages\EditPanelBoxValidation::route('/{record}/edit'),
        ];
    }

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