<?php

namespace App\Filament\Resources;

use App\Filament\Exports\AsrsItemValidationExporter;
use App\Filament\Imports\AsrsItemValidationImporter;
use App\Filament\Resources\AsrsItemValidationResource\Pages;
use App\Filament\Resources\AsrsItemValidationResource\RelationManagers;
use App\Models\AsrsItemValidation;
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\Forms\Get;
use App\Models\Item;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\DateTimePicker;
use App\Models\Plant;
use Illuminate\Support\Facades\Auth;

class AsrsItemValidationResource extends Resource
{
    protected static ?string $model = AsrsItemValidation::class;

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

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->relationship('plant', 'name')
                    ->required()
                    ->disabledOn('edit'),
                Forms\Components\Select::make('item_code')
                    ->label('Item Code')
                    ->reactive()
                    ->options(function (Get $get) {
                        $plantId = $get('plant_id');

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

                        return AsrsItemValidation::where('plant_id', $plantId)
                            ->pluck('item_code', 'item_code');
                    })
                    ->searchable()
                    ->afterStateUpdated(function (callable $set, $state) {
                        $item = AsrsItemValidation::where('item_code', $state)->first();

                        if ($item) {
                            $set('item_description', $item->item_description);
                            $set('uom', $item->uom);
                        } else {
                            $set('item_description', null);
                            $set('uom', null);
                        }
                    })
                    ->disabledOn('edit'),
                Forms\Components\TextInput::make('item_description')
                    ->label('Item Description')
                    ->readOnly()
                    ->reactive()
                    ->disabledOn('edit'),
                Forms\Components\TextInput::make('uom')
                    ->label('UOM')
                    ->readOnly()
                    ->reactive()
                    ->disabledOn('edit'),
                Forms\Components\TextInput::make('material_type')
                    ->label('Material Type')
                    ->readOnly()
                    ->reactive()
                    ->disabledOn('edit'),
                Forms\Components\TextInput::make('material_group')
                    ->label('Material Group')
                    ->readOnly()
                    ->reactive()
                    ->disabledOn('edit'),
                Forms\Components\Select::make('mhe')
                    ->label('MHE')
                    ->options([
                        'Bin1000*800*750' => 'Bin 1000*800*750',
                        'Bin1000*800*1000' => 'Bin 1000*800*1000',
                        'Pallet' => 'Pallet',
                        'ChinaBin' => 'China Bin',
                        'PalletWithPlasticCrate' => 'Pallet With Plastic Crate',
                        'PlasticCrateBig' => 'Plastic Crate Big',
                        'PlasticCrateSmall' => 'Plastic Crate Small',
                        'OutsideStorage' => 'Outside Storage',
                    ]),
                Forms\Components\TextInput::make('bin_quantity')
                    ->label('Bin Quantity'),
                Forms\Components\Select::make('asrs')
                    ->label('ASRS')
                    ->options([
                        'ASRS1' => 'ASRS1',
                        'ASRS2' => 'ASRS2',
                    ]),
                Forms\Components\Select::make('asrs_category')
                    ->label('ASRS Category')
                    ->options([
                        'In' => 'In',
                        'Out' => 'Out',
                    ]),
                // Forms\Components\Select::make('status')
                //     ->label('Status')
                //     ->options([
                //         'Updated' => 'Updated',
                //         'NotUpdated' => 'Not Updated',
                //     ]),
                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;
                    })
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item_code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->searchable(query: function ($query, string $search) {
                        $itemCode = explode('|', trim($search))[0];
                        $query->where('item_code', $itemCode);
                    })
                    // ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item_description')
                    ->label('Item Description')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('uom')
                    ->label('UOM')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('material_type')
                    ->label('Material Type')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('material_group')
                    ->label('Material Group')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('mhe')
                    ->label('MHE')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('bin_quantity')
                    ->label('Bin Quantity')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('asrs')
                    ->label('ASRS')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('asrs_category')
                    ->label('ASRS Category')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->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('asrsItemValidations', 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_code', null);
                            }),
                        Select::make('item_code')
                            ->label('Item Code')
                            ->reactive()
                            ->searchable()
                            ->options(function (callable $get) {

                                $plantId = $get('Plant');

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

                                return AsrsItemValidation::where('plant_id', $plantId)
                                    ->distinct()
                                    ->pluck('item_code', 'item_code')
                                    ->toArray();
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('uom', null);
                            }),
                        TextInput::make('uom')
                            ->label('UOM')
                            ->reactive()
                            ->placeholder('Enter UOM'),
                        Select::make('status')
                            ->label('Status')
                            ->reactive()
                            ->options(function (callable $get) {

                                $plantId = $get('Plant');

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

                                return [
                                    'Updated' => 'Updated',
                                    'NotUpdated' => 'Not Updated',
                                ];
                            }),
                        DateTimePicker::make('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) {

                        $status = $data['status'] ?? 'NotUpdated';
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['item_code']) && empty($data['uom']) && empty($data['status']) && empty($data['created_from']) && empty($data['created_to'])) {
                            return $query->whereRaw('1 = 0');
                            // $query->where('status', 'NotUpdated');
                        }

                        // if (
                        //     empty($data['Plant']) &&
                        //     empty($data['item_code']) &&
                        //     empty($data['uom']) &&
                        //     empty($data['status']) &&
                        //     empty($data['created_from']) &&
                        //     empty($data['created_to'])
                        // ) {
                        //     // $query->where('status', 'NotUpdated');
                        //     $query->where(function ($q) {
                        //         $q->where('status', 'NotUpdated')
                        //         ->orWhereNull('status')
                        //         ->orWhere('status', '');
                        //     });
                        // }

                        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_code'])) {
                            $query->where('item_code', 'like', '%'.$data['item_code'].'%');
                        }
                        if (! empty($data['uom'])) {
                            $query->where('uom', 'like', '%'.$data['uom'].'%');
                        }
                        if (!empty($data['status'])) {

                            if ($data['status'] == 'NotUpdated') {
                                $query->where(function ($q) {
                                    $q->where('status', 'NotUpdated')
                                    ->orWhereNull('status')
                                    ->orWhere('status', '');
                                });
                            } else {
                                $query->where('status', $data['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_code'])) {
                            $indicators[] = 'Item Code: '.$data['item_code'];
                        }

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

                        if (! empty($data['status'])) {
                            $indicators[] = 'Status: '.$data['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(),
                // ->hidden(function ($record): bool {
                //     if (auth()->user()?->hasRole('Super Admin')) {
                //         return false;
                //     }
                //     else{
                //         return trim(($record->status)) == 'Updated';
                //     }
                // }),
                // ->visible(function ($record): bool {
                //     return auth()->user()?->hasRole('SuperAdmin')
                //         || strtolower(trim($record->status ?? '')) != 'updated' || strtolower(trim($record->status ?? '')) == null || strtolower(trim($record->status ?? '')) == '';
                // }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->importer(AsrsItemValidationImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import asrs item validation');
                    }),
                ExportAction::make()
                    ->exporter(AsrsItemValidationExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export asrs item validation');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAsrsItemValidations::route('/'),
            'create' => Pages\CreateAsrsItemValidation::route('/create'),
            'view' => Pages\ViewAsrsItemValidation::route('/{record}'),
            'edit' => Pages\EditAsrsItemValidation::route('/{record}/edit'),
        ];
    }

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