<?php

namespace App\Filament\Resources;

use App\Filament\Exports\WindedSerialValidationErrorExporter;
use App\Filament\Resources\WindedSerialValidationErrorResource\Pages;
use App\Models\Item;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\WindedSerialValidationError;
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\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class WindedSerialValidationErrorResource extends Resource
{
    protected static ?string $model = WindedSerialValidationError::class;

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

    protected static ?string $navigationGroup = 'Laser Marking';

    protected static ?int $navigationSort = 6;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->label('Plant Name')
                            ->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();
                            })
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? $userHas : optional(WindedSerialValidationError::latest()->first())->plant_id ?? null;
                            })
                            ->columnSpan(1) // (['default' => 1, 'sm' => 2])
                            ->required()
                            ->reactive()
                            ->searchable()
                            ->disabled(fn (Get $get) => ! empty($get('id')))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                $set('item_id', null);
                                $set('machine_id', null);

                                if (! $plantId) {
                                    $set('pTeError', 'Please select a plant first.');

                                    return;
                                } else {
                                    $set('pTeError', null);
                                }

                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pTeError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pTeError') ? $get('pTeError') : null)
                            ->hintColor('danger'),
                        Forms\Components\Select::make('item_id')
                            ->label('Item Code')
                            // ->relationship('item', 'code')
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    return [];
                                }

                                return Item::where('plant_id', $plantId)->orderBy('code')->pluck('code', 'id')->toArray();
                            })
                            ->default(function (callable $get) {
                                $plantId = $get('plant_id');
                                // $itemId = $get('item_id');
                                if (! $plantId) {
                                    return null;
                                }

                                return WindedSerialValidationError::where('plant_id', $plantId)->latest()->first()->item_id ?? null;
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive()
                            ->searchable()
                            ->disabled(fn (Get $get) => ! empty($get('id')))
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\Select::make('machine_id')
                            ->label('WORK CENTER')
                            // ->relationship('machine', 'work_center')
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    return [];
                                }

                                return Machine::where('plant_id', $plantId)->orderBy('work_center')->pluck('work_center', 'id')->toArray();
                            })
                            ->default(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    return null;
                                }

                                return WindedSerialValidationError::where('plant_id', $plantId)->latest()->first()->machine_id ?? null;
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive()
                            ->searchable()
                            ->disabled(fn (Get $get) => ! empty($get('id')))
                            ->afterStateUpdated(function (callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('machine_name')
                            ->label('Machine Name')
                            ->placeholder('Scan the Machine Name')
                            ->columnSpan(1)
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('aufnr')
                            ->label('AUFNR')
                            ->placeholder('Scan the AUFNR')
                            ->columnSpan(1)
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('gernr')
                            ->label('GERNR')
                            ->placeholder('Scan the GERNR')
                            ->columnSpan(1)
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('model_type')
                            ->label('Model Type')
                            ->placeholder('Scan the Model Type')
                            ->columnSpan(1)
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('winded_qr')
                            ->label('Winded QR')
                            ->placeholder('Scan the Winded QR')
                            ->columnSpan(1)
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('winded_code')
                            ->label('Winded Code')
                            ->placeholder('Scan the Winded Code')
                            ->columnSpan(1)
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('winded_serial_number')
                            ->label('Winded Serial Number')
                            ->placeholder('Scan the Winded Serial Number')
                            ->columnSpan(1)
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('winded_status')
                            ->label('Winded Status')
                            ->placeholder('Scan the Winded Status')
                            ->columnSpan(1)
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('created_by')
                            ->default(fn () => Filament::auth()->user()?->name)
                            ->readOnly()
                            ->columnSpan(1)
                            ->required(),
                        Forms\Components\Hidden::make('updated_by')
                            ->default(fn () => Filament::auth()->user()?->name)
                            ->columnSpan(1)
                            ->required(),
                        Forms\Components\TextInput::make('id')
                            ->hidden()
                            ->columnSpan(1)
                            ->readOnly(),
                    ])
                    ->columns(['default' => 1, 'sm' => 2]),
            ]);
    }

    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 Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.description')
                    ->label('Description')
                    ->searchable()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('item.category')
                    ->label('Category')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('item.uom')
                    ->label('Unit of Measure')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine_name')
                    ->label('Machine Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('aufnr')
                    ->label('AUFNR')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('gernr')
                    ->label('GERNR')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('model_type')
                    ->label('Model Type')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('winded_status')
                    ->label('Winded Status')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('winded_qr')
                    ->label('Winded QR')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('winded_code')
                    ->label('Winded Code')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('winded_serial_number')
                    ->label('Winded Serial Number')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->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('windedSerialValidationErrors', 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): void {
                                $set('machine', null);
                                $set('item_id', null);
                            }),
                        Select::make('machine')
                            ->label('Search by Work Center')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

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

                                return Machine::whereHas('windedSerialValidationErrors', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('work_center', 'id');
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get): void {
                                // $set('item_id', null);
                                // $set('aufnr', null);
                            }),
                        TextInput::make('machine_name')
                            ->label('Machine Name')
                            ->placeholder('Enter Machine Name'),
                        Select::make('item_id')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

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

                                return Item::whereHas('windedSerialValidationErrors', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('code', 'id');
                            }),
                        TextInput::make('aufnr')
                            ->label('Job Number')
                            ->placeholder('Enter Job Number')
                            ->minlength(7)
                            ->maxlength(10),
                        TextInput::make('gernr')
                            ->label('Serial Number')
                            ->placeholder('Enter Serial Number')
                            ->minlength(9),
                        Select::make('model_type')
                            ->label('Search by Model Type')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return WindedSerialValidationError::whereNotNull('model_type')->select('model_type')->distinct()->pluck('model_type', 'model_type');
                                } else {
                                    return WindedSerialValidationError::where('plant_id', $plantId)->whereNotNull('model_type')->select('model_type')->distinct()->pluck('model_type', 'model_type');
                                }
                            }),
                        Select::make('winded_status')
                            ->label('Search by Winded Status')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return WindedSerialValidationError::whereNotNull('winded_status')->select('winded_status')->distinct()->pluck('winded_status', 'winded_status');
                                } else {
                                    return WindedSerialValidationError::where('plant_id', $plantId)->whereNotNull('winded_status')->select('winded_status')->distinct()->pluck('winded_status', 'winded_status');
                                }
                            }),
                        TextInput::make('winded_qr')
                            ->label('Winded QR')
                            ->placeholder('Enter Winded QR'),
                        Select::make('winded_code')
                            ->label('Search by Winded Code')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return WindedSerialValidationError::whereNotNull('winded_code')->select('winded_code')->distinct()->pluck('winded_code', 'winded_code');
                                } else {
                                    return WindedSerialValidationError::where('plant_id', $plantId)->whereNotNull('winded_code')->select('winded_code')->distinct()->pluck('winded_code', 'winded_code');
                                }
                            }),
                        TextInput::make('winded_serial_number')
                            ->label('Winded Serial Number')
                            ->placeholder('Enter Winded Serial Number'),
                        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),
                        Select::make('created_by')
                            ->label('Search by Created By')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return WindedSerialValidationError::whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                                } else {
                                    return WindedSerialValidationError::where('plant_id', $plantId)->whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                                }
                            }),
                        DateTimePicker::make('updated_from')
                            ->label('Updated From')
                            ->placeholder('Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('updated_to')
                            ->label('Updated To')
                            ->placeholder('Select To DateTime')
                            ->reactive()
                            ->native(false),
                        Select::make('updated_by')
                            ->label('Search by Updated By')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return WindedSerialValidationError::whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
                                } else {
                                    return WindedSerialValidationError::where('plant_id', $plantId)->whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
                                }
                            }),
                    ])
                    ->query(function ($query, array $data) {
                        if (empty($data['Plant']) && empty($data['machine']) && empty($data['machine_name']) && empty($data['item_id']) && empty($data['aufnr']) && empty($data['gernr']) && empty($data['model_type']) && empty($data['winded_status']) && empty($data['winded_qr']) && empty($data['winded_code']) && empty($data['winded_serial_number']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by']) && empty($data['updated_from']) && empty($data['updated_to']) && empty($data['updated_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['machine'])) {
                            $query->where('machine_id', $data['machine']);
                        }

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

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

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

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

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

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

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

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

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

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

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

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

                        if (! empty($data['updated_by'])) {
                            $query->where('updated_by', $data['updated_by']);
                        }
                    })
                    ->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: Choose plant to filter records.';
                            }
                        }

                        if (! empty($data['machine'])) {
                            $indicators[] = 'Work Center: '.Machine::where('id', $data['machine'])->value('work_center');
                        }

                        if (! empty($data['machine_name'])) {
                            $indicators[] = 'Machine Name: '.$data['machine_name'];
                        }

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

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

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

                        if (! empty($data['model_type'])) {
                            $indicators[] = 'Model Type: '.$data['model_type'];
                        }

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

                        if (! empty($data['winded_qr'])) {
                            $indicators[] = 'Winded QR: '.$data['winded_qr'];
                        }

                        if (! empty($data['winded_code'])) {
                            $indicators[] = 'Winded Code: '.$data['winded_code'];
                        }

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

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

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

                        if (! empty($data['created_by'])) {
                            $indicators[] = 'Created By: '.$data['created_by'];
                        }

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

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

                        if (! empty($data['updated_by'])) {
                            $indicators[] = 'Updated By: '.$data['updated_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([
                ExportAction::make()
                    ->label('Export Winded Serial Validation Errors')
                    ->color('warning')
                    ->exporter(WindedSerialValidationErrorExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export winded serial validation errors');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListWindedSerialValidationErrors::route('/'),
            'create' => Pages\CreateWindedSerialValidationError::route('/create'),
            'view' => Pages\ViewWindedSerialValidationError::route('/{record}'),
            'edit' => Pages\EditWindedSerialValidationError::route('/{record}/edit'),
        ];
    }

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