<?php

namespace App\Filament\Resources;

use App\Filament\Resources\WireMasterPackingResource\Pages;
use App\Models\CustomerPoMaster;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\WireMasterPacking;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\DateTimePicker;
use Str;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use App\Filament\Exports\WireMasterPackingExporter;
use App\Filament\Imports\WireMasterPackingImporter;

class WireMasterPackingResource extends Resource
{
    protected static ?string $model = WireMasterPacking::class;

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

    protected static ?string $navigationGroup = 'Master Packing';

    public $importedPoList = [];


    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->label('Plant')
                            ->reactive()
                            ->relationship('plant', 'name')
                            ->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();
                            })
                            ->required(),
                        Forms\Components\Select::make('customer_po_master_id')
                            ->label('Customer PO')
                            ->reactive()
                            ->searchable()
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (empty($plantId)) {
                                    return [];
                                }

                                // return CustomerPoMaster::where('plant_id', $plantId)->pluck('customer_po', 'id');
                                return CustomerPoMaster::where('plant_id', $plantId)->distinct()->pluck('customer_po', 'customer_po');

                            })
                            ->required()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('wire_packing_number', null);
                            }),
                        Forms\Components\TextInput::make('wire_packing_number')
                            ->label('Scan Wire Packing No')
                            ->reactive()
                            ->required()
                            ->readonly()
                            ->extraAttributes([
                                'x-data' => '{ value: "" }',
                                'x-model' => 'value',
                                'x-on:keydown.enter.prevent' => '$wire.processPalletNo()',
                            ])
                            ->suffixAction(fn ($get, $set) => Forms\Components\Actions\Action::make('addWirePackNo')
                                ->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 = "MP-{$year}{$month}";

                                    $lastPallet = WireMasterPacking::where('wire_packing_number', 'like', "{$prefix}%")
                                        ->orderByDesc('wire_packing_number')
                                        ->first();

                                    // if ($lastPallet) {
                                    //     // Extract numeric part after prefix
                                    //     $lastNumber = substr($lastPallet->wire_packing_number, strlen($prefix));
                                    //     $newNumber  = str_pad(((int) $lastNumber) + 1, 3, '0', STR_PAD_LEFT);
                                    // } else {
                                    //     // First pallet of the month
                                    //     $newNumber = '001';
                                    // }

                                    if ($lastPallet) {
                                        $lastNumber = (int) substr(
                                            $lastPallet->wire_packing_number,
                                            strlen($prefix)
                                        );

                                        $newNumber = $lastNumber + 1;

                                        $newNumber = $newNumber < 1000
                                            ? str_pad($newNumber, 3, '0', STR_PAD_LEFT)
                                            : (string) $newNumber;
                                    } else {
                                        $newNumber = '001';
                                    }

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

                                    $set('wire_packing_number', $newPalletNumber);
                                    $set('plant_id', $plantId);

                                    // $livewire->redirectToQrPdf($newPalletNumber);
                                })
                            ),
                        Forms\Components\TextInput::make('process_order')
                            ->label('Process Order')
                            ->reactive()
                            ->readOnly(fn (callable $get) => ! $get('wire_packing_number'))
                            ->extraAttributes([
                                'x-on:keydown.enter.prevent' => '$wire.processOrderSNo()',
                            ]),
                        Forms\Components\TextInput::make('removeSno_number')
                            ->label('Remove Process Order')
                            ->reactive()
                            ->minLength(9)
                            ->readOnly(fn (callable $get) => ! $get('wire_packing_number') || $get('process_order'))
                            ->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\Select::make('pending_pallet_list')
                            ->label('Pending Pallet List')
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('wire_packing_number', $state);
                                $set('pallet_number_locked', false);
                            })
                            ->options(function ($get) {

                                $plantId = $get('plant_id');
                                $customerPo = $get('customer_po_master_id');

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

                                $customerPoIds = CustomerPoMaster::where('plant_id', $plantId)
                                    ->where('customer_po', $customerPo)
                                    ->pluck('id');

                                return WireMasterPacking::query()
                                    ->where('plant_id', $plantId)
                                    ->whereIn('customer_po_master_id', $customerPoIds)
                                    ->where(function ($query) {
                                        $query->whereNull('wire_packing_status')
                                            ->orWhere('wire_packing_status', '');
                                    })
                                    ->whereNotNull('wire_packing_number')
                                    ->orderBy('wire_packing_number', 'asc')
                                    ->pluck('wire_packing_number')
                                    ->unique()
                                    ->mapWithKeys(fn ($number) => [$number => $number])
                                    ->toArray();
                            }),
                        // Forms\Components\Checkbox::make('is_po')
                        //     ->label('PO!')
                        //     ->reactive(),
                        Forms\Components\View::make('forms.components.save-processorder-button'),

                        Forms\Components\Hidden::make('created_by')
                            ->label('Created By'),
                        Forms\Components\Hidden::make('updated_by')
                            ->label('Updated By'),
                    ])
                    ->columns(6),
            ]);
    }

    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('item.code')
                    ->label('Item')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.description')
                    ->label('Description')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('customerPo.customer_po')
                    ->label('Customer PO')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('customerPo.customer_name')
                    ->label('Customer Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('wire_packing_number')
                    ->label('Wire Packing Number')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('process_order')
                    ->label('Process Order')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('weight')
                    ->label('Weight')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('wire_packing_status')
                    ->label('Wire Packing Status')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->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('wireMasterPacking', 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('Item', null);
                            }),
                        Select::make('Item')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

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

                                return Item::whereHas('wireMasterPacking', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('code', 'id');
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('process_order', null);
                            }),
                        TextInput::make('wire_packing_number')
                            ->label('Wire Packing Number')
                            ->reactive()
                            ->placeholder('Enter Wire Packing Number')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('process_order', null);
                            }),
                        TextInput::make('process_order')
                            ->label('Process Order')
                            ->reactive()
                            ->placeholder('Enter Process Order')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Rework', null);
                            }),
                        TextInput::make('customer_po_master_id')
                            ->label('Customer PO')
                            ->reactive()
                            ->placeholder('Enter Customer PO'),
                        Select::make('wire_packing_status')
                            ->label('Wire Packing Status')
                            ->reactive()
                            ->options([
                                'Completed' => 'Completed',
                                'Pending' => 'Pending',
                            ]),
                        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['Item']) && empty($data['process_order']) && empty($data['wire_packing_number']) && empty($data['customer_po_master_id']) && empty($data['wire_packing_status']) && 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['Item'])) {
                            $query->where('item_id', $data['Item']);
                        }

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

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

                        if (!empty($data['customer_po_master_id'])) {

                            // $customerPoId = CustomerPoMaster::where('customer_po', $data['customer_po_master_id'])
                            //     ->where('plant_id', $data['Plant'])
                            //     ->value('id');
                            $customerPoIds = CustomerPoMaster::where('customer_po', $data['customer_po_master_id'])
                            ->where('plant_id', $data['Plant'])
                            ->pluck('id');

                            // $query->where('customer_po_master_id', $customerPoId);
                            $query->whereIn('customer_po_master_id', $customerPoIds);
                        }

                        if (! empty($data['wire_packing_status'])) {
                            if ($data['wire_packing_status'] == 'Pending') {
                                $query->where(function ($q) {
                                    $q->whereNull('wire_packing_status')
                                    ->orWhere('wire_packing_status', '');
                                });
                            } else {
                                $query->where('wire_packing_status', $data['wire_packing_status']);
                            }
                        }

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

                        if (! empty($data['created_to'])) {
                            $query->where('created_at', '<=', $data['created_to']);
                        }
                        // $query->orderBy('created_at', 'asc');
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

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

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

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

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

                        if (! empty($data['wire_packing_number'])) {
                            $indicators[] = 'Wire Packing Number: '.$data['wire_packing_number'];
                        }

                        if (! empty($data['customer_po_master_id'])) {
                            $indicators[] = 'Customer PO: '.$data['customer_po_master_id'];
                        }

                        if (! empty($data['wire_packing_status'])) {
                            $indicators[] = 'Wire Packing Status: '.$data['wire_packing_status'];
                        }

                        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 Wire Packing Master')
                    ->color('warning')
                    ->importer(WireMasterPackingImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import wire packing master');
                    }),
                ExportAction::make()
                    ->label('Export Wire Packing Master')
                    ->color('warning')
                    ->exporter(WireMasterPackingExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export wire packing master');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListWireMasterPackings::route('/'),
            'create' => Pages\CreateWireMasterPacking::route('/create'),
            'view' => Pages\ViewWireMasterPacking::route('/{record}'),
            'edit' => Pages\EditWireMasterPacking::route('/{record}/edit'),
        ];
    }

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