<?php

namespace App\Filament\Resources;

use App\Filament\Exports\PanelGrMasterExporter;
use App\Filament\Imports\PanelGrMasterImporter;
use App\Filament\Resources\PanelGrMasterResource\Pages;
use App\Filament\Resources\PanelGrMasterResource\RelationManagers;
use App\Models\Item;
use App\Models\PalletValidation;
use App\Models\PanelGrMaster;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Closure;

class PanelGrMasterResource extends Resource
{
    protected static ?string $model = PanelGrMaster::class;

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

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->reactive()
                    ->searchable()
                    ->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();
                    })
                    ->afterStateUpdated(function (callable $set) {
                        $set('item_id', null);
                        $set('document_number', null);
                        $set('invoice_number', null);
                        $set('supplier_number', null);
                        $set('quantity', '1');
                    })
                    ->required(),
                Forms\Components\Select::make('item_id')
                    ->label('Item Code')
                    ->reactive()
                    ->searchable()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (empty($plantId)) {
                            return [];
                        }

                        return Item::where('plant_id', $plantId)->pluck('code', 'id');
                    })
                    ->afterStateUpdated(function (callable $set) {
                        $set('document_number', null);
                        $set('invoice_number', null);
                        $set('supplier_number', null);
                        $set('quantity', '1');
                    })
                    ->required(),
                Forms\Components\TextInput::make('document_number')
                    ->label('Document Number')
                    ->required(),
                Forms\Components\TextInput::make('invoice_number')
                    ->label('Invoice Number')
                    ->required(),
                Forms\Components\TextInput::make('supplier_number')
                    ->label('Supplier Number')
                    ->required(),
                Forms\Components\TextInput::make('inspection_lot_number')
                    ->label('Inspection Lot Number')
                    ->required(),
                Forms\Components\TextInput::make('quantity')
                    ->label('Quantity')
                    ->numeric()
                    ->default(1)
                    ->minValue(1)
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function (callable $set, $state) {
                        if ((float) $state == 0) {
                            $set('quantity', null);
                        }
                    }),
                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),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant Name')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Item Code')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('document_number')
                    ->label('Document Number')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('invoice_number')
                    ->label('Invoice Number')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('supplier_number')
                    ->label('Supplier Number')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('inspection_lot_number')
                    ->label('Inspection Lot Number')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('quantity')
                    ->label('Quantity')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->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('Select Plant')
                            ->nullable()
                            ->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();
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get): void {
                                $set('scanned_by', 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('panelGrMasters', 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('document_number')
                            ->label('Document Number')
                            ->reactive()
                            ->placeholder('Enter Document Number')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Rework', null);
                            }),
                        TextInput::make('invoice_number')
                            ->label('Invoice Number')
                            ->reactive()
                            ->placeholder('Enter Invoice Number')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Rework', null);
                            }),
                        TextInput::make('supplier_number')
                            ->label('Supplier Number')
                            ->reactive()
                            ->placeholder('Enter Supplier Number')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Rework', null);
                            }),
                        DateTimePicker::make(name: 'created_from')
                            ->label('Created From')
                            ->placeholder(placeholder: 'Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('created_to')
                            ->label('Created To')
                            ->placeholder(placeholder: 'Select To DateTime')
                            ->reactive()
                            ->native(false),
                    ])
                    ->query(function ($query, array $data) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['document_number']) && empty($data['invoice_number']) && empty($data['supplier_number']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by'])) {
                            return $query->whereRaw('1 = 0');
                        }

                        if (! empty($data['Plant'])) { // $plant = $data['Plant'] ?? null
                            $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['document_number'])) {
                            $query->where('document_number', 'like', '%' . $data['document_number'] . '%');
                        }

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

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

                        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: '.Plant::where('id', $data['Plant'])->value('name');
                        } else {
                            $userHas = Filament::auth()->user()->plant_id;

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

                        if (! empty($data['document_number'])) {
                            $indicators[] = 'Doc No: '.$data['document_number'];
                        }

                        if (! empty($data['invoice_number'])) {
                            $indicators[] = 'Invoice No: '.$data['invoice_number'];
                        }

                        if (! empty($data['supplier_number'])) {
                            $indicators[] = 'Supplier No: '.$data['supplier_number'];
                        }

                        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 GR Masters')
                    ->color('warning')
                    ->importer(PanelGrMasterImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import panel gr master');
                    }),
                ExportAction::make()
                    ->label('Export Panel GR Masters')
                    ->color('warning')
                    ->exporter(PanelGrMasterExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export panel gr master');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPanelGrMasters::route('/'),
            'create' => Pages\CreatePanelGrMaster::route('/create'),
            'view' => Pages\ViewPanelGrMaster::route('/{record}'),
            'edit' => Pages\EditPanelGrMaster::route('/{record}/edit'),
        ];
    }

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