<?php

namespace App\Filament\Resources;

use App\Filament\Resources\WireMasterPackingResource\Pages;
use App\Models\CustomerPoMaster;
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;

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

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

    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');
                            })
                            ->required(),
                        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');

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

                                return WireMasterPacking::query()
                                    ->where('plant_id', $plantId)
                                    ->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(),
            ])
            ->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(),
                ]),
            ]);
    }

    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,
            ]);
    }
}
