<?php

namespace App\Filament\Resources;

use App\Filament\Exports\CharacteristicValueExporter;
use App\Filament\Imports\CharacteristicValueImporter;
use App\Filament\Resources\CharacteristicValueResource\Pages;
use App\Models\CharacteristicValue;
use App\Models\Item;
use App\Models\Line;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\ProductCharacteristicsMaster;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
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\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Validation\Rule;
use Str;

class CharacteristicValueResource extends Resource
{
    protected static ?string $model = CharacteristicValue::class;

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

    protected static ?string $navigationGroup = 'Process Order';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant Name')
                    ->nullable()
                    ->searchable()
                    ->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();
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->default(function () {
                        $userHas = Filament::auth()->user()->plant_id;

                        return ($userHas && strlen($userHas) > 0) ? $userHas : optional(CharacteristicValue::latest()->first())->plant_id;
                    })
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                        $plantId = $get('plant_id');
                        $set('line_id', null);
                        $set('item_id', null);
                        $set('machine_id', null);
                        $set('process_order', null);
                        $set('coil_number', null);
                        $set('observed_value', null);
                        $set('status', 'NotOk');
                        $set('updated_by', Filament::auth()->user()?->name);
                        if (! $plantId) {
                            $set('poPlantError', 'Please select a plant first.');
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('poPlantError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('poPlantError') ? $get('poPlantError') : null)
                    ->hintColor('danger')
                    ->required(),
                Forms\Components\Select::make('line_id')
                    ->label('Line Name')
                    ->nullable()
                    ->searchable()
                    ->reactive()
                    ->options(function (callable $get) {
                        if (! $get('plant_id')) {
                            return [];
                        }

                        return Line::where('plant_id', $get('plant_id'))
                            ->pluck('name', 'id')
                            ->toArray();
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                        $plantId = $get('plant_id');
                        $set('item_id', null);
                        $set('machine_id', null);
                        $set('process_order', null);
                        $set('coil_number', null);
                        $set('observed_value', null);
                        $set('status', 'NotOk');
                        $set('updated_by', Filament::auth()->user()?->name);
                        if (! $plantId) {
                            $set('line_id', null);
                            $set('poPlantError', 'Please select a plant first.');
                        }
                    })
                    ->required(),
                Forms\Components\Select::make('item_id')
                    ->label('Item Code')
                    ->nullable()
                    ->searchable()
                    ->reactive()
                    ->options(function (callable $get) {
                        if (! $get('plant_id') || ! $get('line_id')) {
                            return [];
                        }

                        return Item::where('plant_id', $get('plant_id'))
                            ->pluck('code', 'id')
                            ->toArray();
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                        $plantId = $get('plant_id');
                        $set('machine_id', null);
                        $set('process_order', null);
                        $set('coil_number', null);
                        $set('observed_value', null);
                        $set('status', 'NotOk');
                        $set('updated_by', Filament::auth()->user()?->name);
                        if (! $plantId) {
                            $set('item_id', null);
                            $set('poPlantError', 'Please select a plant first.');
                        }
                    })
                    ->required(),
                Forms\Components\Select::make('machine_id')
                    ->label('Work Center')
                    ->nullable()
                    ->searchable()
                    ->reactive()
                    ->options(function (callable $get) {
                        if (! $get('plant_id') || ! $get('line_id') || ! $get('item_id')) {
                            return [];
                        }

                        return Machine::where('plant_id', $get('plant_id'))
                            ->where('line_id', $get('line_id'))
                            ->pluck('work_center', 'id')
                            ->toArray();
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                        $plantId = $get('plant_id');
                        $set('process_order', null);
                        $set('coil_number', null);
                        $set('observed_value', null);
                        $set('status', 'NotOk');
                        $set('updated_by', Filament::auth()->user()?->name);
                        if (! $plantId) {
                            $set('machine_id', null);
                            $set('poPlantError', 'Please select a plant first.');
                        }
                    })
                    ->required(),
                Forms\Components\TextInput::make('process_order')
                    ->label('Process Order')
                    ->reactive()
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                        $plantId = $get('plant_id');
                        $set('coil_number', null);
                        $set('observed_value', null);
                        $set('status', 'NotOk');
                        $set('updated_by', Filament::auth()->user()?->name);
                        if (! $plantId) {
                            $set('process_order', null);
                            $set('poPlantError', 'Please select a plant first.');
                        }
                    })
                    ->required(),
                Forms\Components\TextInput::make('coil_number')
                    ->label('Coil Number')
                    // ->reactive()
                    // ->afterStateUpdated(function ($state, $set, callable $get) {
                    //     $plantId = $get('plant_id');
                    //     $set('status', 'NotOk');
                    //     if (! $plantId) {
                    //         $set('poPlantError', 'Please select a plant first.');
                    //     }
                    // })
                    // ->required(),
                    ->label('Coil Number')
                    ->default('0')
                    ->numeric()
                    ->reactive()
                    ->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
                        $plantId = $get('plant_id');
                        $processOrder = $get('process_order');
                        // $coilNo = $get('coil_number');
                        $set('poPlantError', null);
                        $set('observed_value', null);
                        $set('status', 'NotOk');
                        $set('coilNumberError', null);
                        $set('updated_by', Filament::auth()->user()?->name);
                        if (! $plantId) {
                            $set('coil_number', null);
                            $set('poPlantError', 'Please select a plant first.');
                        } elseif (! $processOrder) {
                            $set('coil_number', null);
                        }
                        // elseif ($coilNo || $coilNo == '0') {
                        //     $existing = CharacteristicValue::where('plant_id', $plantId)
                        //         ->where('process_order', $processOrder)
                        //         ->where('coil_number', $coilNo)
                        //         ->first();

                        //     if ($existing && ! $get('id')) {
                        //         // $set('coil_number', null);
                        //         $set('coilNumberError', "Duplicate Coil : '{$coilNo}' found!");
                        //     } else {
                        //         $set('coilNumberError', null);
                        //     }
                        // }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('coilNumberError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('coilNumberError') ? $get('coilNumberError') : null)
                    ->hintColor('danger')
                    ->rule(function (callable $get) {
                        return Rule::unique('characteristic_values', 'coil_number')
                            ->where('plant_id', $get('plant_id'))
                            ->where('process_order', $get('process_order'))
                            ->ignore($get('id')); // Ignore current record during updates
                    })
                    ->required(),
                Forms\Components\TextInput::make('observed_value')
                    ->label('Observed Value')
                    ->reactive()
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                        $plantId = $get('plant_id');
                        $itemId = $get('item_id');
                        $lineId = $get('line_id');
                        $machineId = $get('machine_id');
                        $set('updated_by', Filament::auth()->user()?->name);

                        if (! $plantId || ! $itemId || ! $lineId || ! $machineId) {
                            $set('observed_value', null);
                            $set('status', 'NotOk');

                            return;
                        }

                        if (Str::length($state) <= 0 || ! is_numeric($state) || ! preg_match('/^\d+(\.\d+)?$/', $state)
                        ) {
                            $set('status', 'NotOk');

                            return;
                        }

                        $specVal = ProductCharacteristicsMaster::where('plant_id', $plantId)->where('item_id', $itemId)->where('line_id', $lineId)->where('machine_id', $machineId)->first();
                        if (! $specVal) {
                            $set('status', 'NotOk');

                            return;
                        }

                        $lowLimit = $specVal?->lower ?? 0;
                        $uppLimit = $specVal?->upper ?? 0;

                        if (Str::length($lowLimit) <= 0 || ! is_numeric($lowLimit) || ! preg_match('/^\d+(\.\d+)?$/', $lowLimit)
                        ) {
                            $set('status', 'NotOk');

                            return;
                        } elseif (Str::length($uppLimit) <= 0 || ! is_numeric($uppLimit) || ! preg_match('/^\d+(\.\d+)?$/', $uppLimit)
                        ) {
                            $set('status', 'NotOk');

                            return;
                        }

                        if (($lowLimit == 0 && $uppLimit == 0) || ($uppLimit == 0)) {
                            $set('status', 'NotOk');

                            return;
                        }

                        if ($lowLimit > $state || $uppLimit < $state) {
                            $set('status', 'NotOk');

                            return;
                        }

                        $set('status', 'Ok');
                    })
                    ->required(),
                Forms\Components\TextInput::make('status')// Select
                    ->label('Status')
                    // ->options([
                    //     'Ok' => 'OK',
                    //     'NotOk' => 'Not Ok',
                    // ])
                    ->reactive()
                    ->default('NotOk')
                    ->readOnly()
                    ->required(),
                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),
                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
            ]);
    }

    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('line.name')
                    ->label('Line Name')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Item Code')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.description')
                    ->label('Item Description')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('process_order')
                    ->label('Process Order')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('coil_number')
                    ->label('Coil Number')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine.name')
                    ->label('Spec. Value')
                    // ->searchable()
                    ->formatStateUsing(function ($record) {
                        $specVal = ProductCharacteristicsMaster::where('plant_id', $record->plant_id)->where('item_id', $record->item_id)->where('line_id', $record->line_id)->where('machine_id', $record->machine_id)->first();

                        // return $record?->plant_id.'-'.$record?->item_id.'-'.$record->line_id.'-'.$record?->machine_id;
                        return $specVal?->lower.' - '.$specVal?->upper;
                    })
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('observed_value')
                    ->label('Observed value')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->searchable()
                    // ->formatStateUsing(function ($record) {
                    //     return empty($record->status == 'Ok') ? 'Ok' : 'Not Ok';
                    // })
                    ->color(fn (string $state): string => match ($state) {
                        'Ok' => 'success',
                        'Not Ok' => 'danger',
                        'NotOk' => 'danger',
                        default => 'gray',
                    })
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->searchable()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            // ->filters([
            //     Tables\Filters\TrashedFilter::make(),
            // ])
            ->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('characteristicValues', 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);
                                $set('Machine', null);
                            }),
                        Select::make('Line')
                            ->label('Search by Line Name')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');

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

                                return Line::whereHas('characteristicValues', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('name', 'id');
                                // return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : [];
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Item', null);
                                $set('Machine', 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('characteristicValues', function ($query) use ($plantId) {
                                    if ($plantId) {
                                        $query->where('plant_id', $plantId);
                                    }
                                })->pluck('code', 'id');
                                // return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : [];
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('process_order', null);
                            }),
                        Select::make('Machine')
                            ->label('Search by Work Center')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                $lineId = $get('Line');

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

                                return Machine::whereHas('characteristicValues', function ($query) use ($plantId, $lineId) {
                                    if ($plantId && $lineId) {
                                        $query->where('plant_id', $plantId)->where('line_id', $lineId);
                                    }
                                })->pluck('work_center', 'id');
                                // return $plantId ? Item::where('plant_id', $plantId)->pluck('code', 'id') : [];
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('process_order', null);
                            }),
                        TextInput::make('process_order')
                            ->label('Process Order')
                            ->placeholder('Enter Process Order'),
                        TextInput::make('coil_number')
                            ->label('Coil Number')
                            ->placeholder(placeholder: 'Enter Coil Number'),
                        Select::make('status')
                            ->label('Status')
                            ->options([
                                'Ok' => 'OK',
                                'NotOk' => 'Not Ok',
                            ]),
                        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['Line']) && empty($data['Item']) && empty($data['Machine']) && empty($data['process_order']) && empty($data['coil_number']) && empty($data['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['Line'])) {
                            $query->where('line_id', $data['Line']);
                        }

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

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

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

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

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

                        if (! empty($data['Line'])) {
                            $indicators[] = 'Line Name: '.Line::where('id', $data['Line'])->value('name');
                        }

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

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

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

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

                        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(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->importer(CharacteristicValueImporter::class)
                    ->label('Import Characteristic Value')
                    ->color('warning')
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import characteristic value');
                    }),
                ExportAction::make()
                    ->exporter(CharacteristicValueExporter::class)
                    ->label('Export Characteristic Value')
                    ->color('warning')
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export characteristic value');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCharacteristicValues::route('/'),
            'create' => Pages\CreateCharacteristicValue::route('/create'),
            'view' => Pages\ViewCharacteristicValue::route('/{record}'),
            'edit' => Pages\EditCharacteristicValue::route('/{record}/edit'),
        ];
    }

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