<?php

namespace App\Filament\Resources;

use App\Filament\Exports\PalletValidationExporter;
use App\Filament\Imports\PalletValidationImporter;
use App\Filament\Resources\PalletValidationResource\Pages;
use App\Models\LocatorInvoiceValidation;
use App\Models\PalletValidation;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class PalletValidationResource extends Resource
{
    protected static ?string $model = PalletValidation::class;

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

    protected static ?string $navigationGroup = 'Export Dispatch';

    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {

        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->label('Plant')
                            ->relationship('plant', 'name')
                            ->required()
                            ->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::pluck('name', 'id')->toArray();
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('pallet_number', null);
                                $set('serial_number', null);
                                $set('removeSno_number', null);
                                $set('Sno_quantity', 0);
                                $set('pending_pallet_list', null);
                            }),
                        Forms\Components\TextInput::make('pallet_number')
                            ->label('Scan Pallet No')
                            ->reactive()
                            ->required()
                            ->readonly() // fn ($get) => (bool)$get('pallet_number_locked') || $get('serial_number') || $get('removeSno_number')
                            ->extraAttributes([
                                'x-data' => '{ value: "" }',
                                'x-model' => 'value',
                                'x-on:keydown.enter.prevent' => '$wire.processPalletNo()',
                            ])
                            ->suffixAction(fn ($get, $set) => Forms\Components\Actions\Action::make('addPallet')
                                ->label('')
                                ->button()
                                ->icon('heroicon-o-plus')
                                ->color('primary')
                                ->extraAttributes([
                                    'class' => 'p-1 w-7 h-7',
                                ])
                                ->action(function ($get, $set, $livewire) {
                                    $plantId = $get('plant_id');

                                    session(['pallet_clicked_time' => now()->toDateTimeString()]);

                                    session(['pallet_created_by' => Filament::auth()->user()->name]);

                                    $year = now()->format('y');
                                    $month = now()->format('m');
                                    $prefix = "EP-{$year}{$month}";

                                    $lastPallet1 = PalletValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first(); // ->where('plant_id', $plantId)
                                    $lastPallet2 = LocatorInvoiceValidation::where('pallet_number', 'like', "{$prefix}%")->orderByDesc('pallet_number')->first();
                                    $newNumber = '001'; // $lastPallet ? str_pad(intval(substr($lastPallet->pallet_number, -3)) + 1, 3, '0', STR_PAD_LEFT) : '001';
                                    if ($lastPallet1 && $lastPallet2) {
                                        $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix));
                                        $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix));
                                        if (intval($serialPart1) > intval($serialPart2)) {
                                            $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT);
                                        } else {
                                            $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT);
                                        }
                                    } elseif ($lastPallet1) {
                                        $serialPart1 = substr($lastPallet1->pallet_number, strlen($prefix));
                                        // OR
                                        // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number);
                                        $newNumber = str_pad(intval($serialPart1) + 1, strlen($serialPart1), '0', STR_PAD_LEFT);
                                    } elseif ($lastPallet2) {
                                        $serialPart2 = substr($lastPallet2->pallet_number, strlen($prefix));
                                        // OR
                                        // $serialPart = str_replace($prefix, '', $lastPallet->pallet_number);
                                        $newNumber = str_pad(intval($serialPart2) + 1, strlen($serialPart2), '0', STR_PAD_LEFT);
                                    }

                                    $newPalletNumber = "{$prefix}{$newNumber}";

                                    $set('pallet_number', $newPalletNumber);
                                    $set('pallet_number_locked', true);
                                    $set('plant_id', $plantId);

                                    $livewire->redirectToQrPdf($newPalletNumber);
                                })
                            ),

                        Forms\Components\TextInput::make('serial_number')
                            ->label('Scan Serial No')
                            ->reactive()
                            ->minLength(9)
                            ->readOnly(fn (callable $get) => ! $get('pallet_number') || $get('removeSno_number'))
                            ->extraAttributes([
                                    'x-on:keydown.enter.prevent' => '$wire.processPalletSNo()',
                                ]),
                        Forms\Components\TextInput::make('removeSno_number')
                            ->label('Remove Serial No')
                            ->reactive()
                            ->minLength(9)
                            ->readOnly(fn (callable $get) => ! $get('pallet_number') || $get('serial_number'))
                            ->extraAttributes([
                                    'x-data' => '{ value: "" }',
                                    'x-model' => 'value',
                                    'x-on:keydown.enter.prevent' => '$wire.processRemoveSNo()',
                                ]),

                        Forms\Components\TextInput::make('Sno_quantity')
                            ->label('SNo. Quantity')
                            ->readOnly()
                            ->default('0'),
                        Forms\Components\Hidden::make('created_by')
                            ->default(Filament::auth()->user()?->name),
                        Forms\Components\Hidden::make('scanned_by')
                            ->default(Filament::auth()->user()?->name),
                        Forms\Components\Hidden::make('pallet_number_locked')
                            ->default(false),
                        Forms\Components\Select::make('pending_pallet_list')
                            ->label('Pending Pallet List')
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('pallet_number', $state);
                                $set('pallet_number_locked', false);
                            })
                            ->options(function ($get) {

                                $plantId = $get('plant_id');

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

                                return PalletValidation::query()
                                    ->where('plant_id', $plantId)
                                    ->where(function ($query) {
                                        $query->whereNull('pallet_status')
                                            ->orWhere('pallet_status', '');
                                    })
                                    ->whereNotNull('pallet_number')
                                    ->orderBy('pallet_number', 'asc')
                                    ->pluck('pallet_number')
                                    ->unique()
                                    ->mapWithKeys(fn ($number) => [$number => $number])
                                    ->toArray();
                            }),

                        Forms\Components\View::make('forms.components.save-pallet-button'),
                    ])
                    ->columns(5),
                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),

            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                // Tables\Columns\TextColumn::make('id')
                //     ->label('ID')
                //     ->numeric()
                //     ->sortable(),
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->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()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pallet_number')
                    ->label('Pallet Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('serial_number')
                    ->label('Serial Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('pallet_status')
                    ->label('Pallet Status')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('locator_number')
                    ->label('Locator Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('locator_quantity')
                    ->label('Locator Quantity')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('scanned_by')
                    ->label('Scanned By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('scanned_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            // ->filters([
            //     Tables\Filters\TrashedFilter::make(),
            // ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        Select::make('Plant')
                            ->label('Select Plant')
                            ->nullable()
                            // ->options(function () {
                            //     return Plant::pluck('name', 'id');
                            // })
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get): void {
                                $set('pallet_number', null);
                                $set('serial_number', null);
                                $set('pallet_status', null);
                                $set('locator_number', null);
                                $set('locator_quantity', null);
                                $set('created_from', null);
                                $set('created_to', null);
                                $set('created_by', null);
                                $set('scanned_from', null);
                                $set('scanned_to', null);
                                $set('scanned_by', null);
                            }),
                        Select::make('pallet_number')
                            ->label('Pallet Number')
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return [];
                                }

                                return PalletValidation::where('plant_id', $plantId)
                                    // ->whereNotNull('pallet_number')
                                    // ->where('pallet_number', '!=', '')
                                    ->where('pallet_number', 'like', 'EP-'.'%')
                                    // ->where(function($query) {
                                    //     $query->where('pallet_number', '!=', null)->where('pallet_number', '!=', '');
                                    // })
                                    ->orderBy('pallet_number', 'desc')
                                    ->get()
                                    // ->unique('pallet_number')
                                    ->pluck('pallet_number', 'pallet_number')
                                    ->toArray();
                            })
                            ->searchable()
                            ->reactive(),
                        TextInput::make('serial_number')
                            ->label('Serial Number')
                            ->placeholder(placeholder: 'Enter Serial Number'),
                        Select::make('pallet_status')
                            ->label('Pallet Status')
                            ->options([
                                'Completed' => 'Completed',
                            ]),
                        Select::make('locator_number')
                            ->label('Locator Number')
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return [];
                                }

                                return PalletValidation::where('plant_id', $plantId)
                                    ->whereNotNull('locator_number')
                                    ->where('locator_number', '!=', '')
                                    ->orderBy('locator_number', 'asc')
                                    ->get()
                                    ->unique('locator_number')
                                    ->pluck('locator_number', 'locator_number')
                                    ->toArray();
                            })
                            ->searchable()
                            ->reactive(),
                        Select::make('locator_quantity')
                            ->label('Locator Quantity')
                            ->options([
                                0 => 0,
                                1 => 1,
                                2 => 2,
                            ])
                            ->reactive(),
                        DateTimePicker::make(name: 'created_from')
                            ->label('Created From')
                            ->placeholder(placeholder: 'Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('created_to')
                            ->label('Created To')
                            ->placeholder(placeholder: 'Select To DateTime')
                            ->reactive()
                            ->native(false),
                        TextInput::make('created_by')
                            ->label('Created By')
                            ->placeholder(placeholder: 'Enter Created By'),
                        DateTimePicker::make(name: 'scanned_from')
                            ->label('Scanned From')
                            ->placeholder(placeholder: 'Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('scanned_to')
                            ->label('Scanned To')
                            ->placeholder(placeholder: 'Select To DateTime')
                            ->reactive()
                            ->native(false),
                        TextInput::make('scanned_by')
                            ->label('Scanned By')
                            ->placeholder(placeholder: 'Enter Scanned By'),
                    ])
                    ->query(function ($query, array $data) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['pallet_number']) && empty($data['serial_number']) && empty($data['pallet_status']) && empty($data['locator_number']) && $data['locator_quantity'] == null && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by']) && empty($data['scanned_from']) && empty($data['scanned_to']) && empty($data['scanned_by'])) {
                            return $query->whereRaw('1 = 0');
                        }

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

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

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

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

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

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

                        if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { // isset($data['locator_quantity']) &&
                            $query->where('locator_quantity', $data['locator_quantity']); // (int)
                        }

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

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

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

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

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

                        if (! empty($data['scanned_by'])) {
                            $query->where('scanned_by', $data['scanned_by']);
                        }
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

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

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

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

                        if (! empty($data['pallet_status'])) {
                            $indicators[] = 'Pallet Status: '.$data['pallet_status'];
                        }

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

                        // if (!empty($data['locator_quantity'])) {
                        //     $indicators[] = 'Locator Quantity: ' . $data['locator_quantity'];
                        // }
                        if ($data['locator_quantity'] != null && $data['locator_quantity'] != '') { // isset($data['locator_quantity']) &&
                            $indicators[] = 'Locator Quantity: '.$data['locator_quantity'];
                        }

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

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

                        if (! empty($data['created_by'])) {
                            $indicators[] = 'Created By: '.$data['created_by'];
                        }
                        if (! empty($data['scanned_from'])) {
                            $indicators[] = 'Scanned From: '.$data['scanned_from'];
                        }
                        if (! empty($data['scanned_to'])) {
                            $indicators[] = 'Scanned To: '.$data['scanned_to'];
                        }
                        if (! empty($data['scanned_by'])) {
                            $indicators[] = 'Scanned By: '.$data['scanned_by'];
                        }

                        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([
            ->headerActions([
                Tables\Actions\Action::make('reprint_pallet')
                    ->label('Re-Print Pallet QR')
                    ->form([
                        Forms\Components\Section::make()
                            ->schema([
                                Forms\Components\Select::make('plant')
                                    ->label('Select Plant')
                                    // ->options(Plant::pluck('name', 'id')->toArray())
                                    ->options(function (callable $get) {
                                        $userHas = Filament::auth()->user()->plant_id;

                                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                                    })
                                    ->required()
                                    ->reactive()
                                    ->columnSpan(2),
                                Forms\Components\Select::make('pallet_list')
                                    ->label('Select Pallet')
                                    ->searchable()
                                    ->required()
                                    ->reactive()
                                    ->columnSpan(1)
                                    // ->optionsLimit(500)
                                    ->options(function (callable $get) {
                                        $plantId = $get('plant');

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

                                        return PalletValidation::query()->where('plant_id', $plantId)
                                            // ->whereNotNull('pallet_number')
                                            // ->where('pallet_number', '!=', '')
                                            ->where('pallet_number', 'like', 'EP-'.'%')
                                            ->select('pallet_number')
                                            ->distinct()
                                            ->orderBy('pallet_number', 'desc')
                                            ->pluck('pallet_number', 'pallet_number')
                                            ->toArray();
                                    }),
                            ])
                            ->columns(['default' => 1, 'sm' => 3]),
                    ])
                    ->action(function (array $data) {
                        $selectedPalletNumber = $data['pallet_list'];

                        return redirect()->route('download-reprint-qr-pdf', ['palletNo' => $selectedPalletNumber]);

                    })
                    ->visible(function () {
                        return Filament::auth()->user()->can('view reprint pallet number');
                    }),
                ImportAction::make()
                    ->importer(PalletValidationImporter::class)
                    ->label('Import Pallet')
                    ->color('warning')
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import pallet validation');
                    }),
                ExportAction::make()
                    ->exporter(PalletValidationExporter::class)
                    ->label('Export Pallet')
                    ->color('warning')
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export pallet validation');
                    }),
            ]);
    }

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

    public static function getNavigationLabel(): string
    {
        return 'Scan Pallet';
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPalletValidations::route('/'),
            'create' => Pages\CreatePalletValidation::route('/create'),
            'view' => Pages\ViewPalletValidation::route('/{record}'),
            'edit' => Pages\EditPalletValidation::route('/{record}/edit'),
        ];
    }

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