<?php

namespace App\Filament\Resources;

use App\Filament\Exports\RejectReasonExporter;
use App\Filament\Imports\RejectReasonImporter;
use App\Filament\Resources\RejectReasonResource\Pages;
use App\Filament\Resources\RejectReasonResource\RelationManagers;
use App\Models\Item;
use App\Models\Line;
use App\Models\Plant;
use App\Models\ProductionQuantity;
use App\Models\QualityValidation;
use App\Models\RejectReason;
use App\Models\StickerMaster;
use App\Models\WorkGroupMaster;
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\Forms\Components\Section;
use Filament\Facades\Filament;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Tables\Filters\Filter;
use Filament\Forms\Components\TextInput;

class RejectReasonResource extends Resource
{
    protected static ?string $model = RejectReason::class;

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

    protected static ?string $navigationGroup = 'Production Reject';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                 Section::make('')
                ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->reactive()
                    ->relationship('plant', 'name')
                    ->required()
                    ->columnSpan(1)
                    ->options(function (callable $get) {
                        $userHas = Filament::auth()->user()->plant_id;
                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                    })
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                            $plantId = $get('plant_id');

                            if (!$plantId) {
                                $set('pqPlantError', 'Please select a plant first.');
                                $set('line_id', null);
                                $set('work_group_master_id', null);
                                $set('code', null);
                                $set('reason', null);
                                return;
                            }

                            $set('validationError', null);
                            $set('pqPlantError', null);
                            $set('line_id', null);
                            $set('work_group_master_id', null);
                            $set('code', null);
                            $set('reason', null);
                        })
                    ->hint(fn ($get) => $get('pqPlantError') ? $get('pqPlantError') : null)
                    ->hintColor('danger'),
                Forms\Components\Select::make('line_id')
                    ->label('Line')
                    //->relationship('line', 'name')
                    ->required()
                    ->columnSpan(1)
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');

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

                        return Line::where('plant_id', $plantId)
                            ->pluck('name', 'id')
                            ->toArray();
                    })
                    ->reactive()
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                            $plantId = $get('plant_id');
                            if (!$plantId) {
                                $set('pqLineError', 'Please select a line.');
                                $set('name', null);
                                $set('description', null);
                                $set('operation_number', null);
                                return;
                            }

                            $set('validationError', null);
                            $set('pqPlantError', null);
                            $set('work_group_master_id', null);
                            $set('code', null);
                            $set('reason', null);
                        })
                    ->hint(fn ($get) => $get('pqLineError') ? $get('pqLineError') : null)
                    ->hintColor('danger'),
                Forms\Components\Select::make('work_group_master_id')
                    ->label('Work Group Master')
                    ->columnSpan(1)
                    ->reactive()
                    //->relationship('workGroupMaster', 'name')
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');

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

                        return WorkGroupMaster::where('plant_id', $plantId)
                            ->pluck('name', 'id')
                            ->toArray();
                    })
                    ->required()
                    ->afterStateUpdated(function ($state, $set, callable $get) {
                            $workId = $get('work_group_master_id');
                            if (!$workId) {
                                $set('pqWorkError', 'Please select a Work Group Name.');
                                $set('code', null);
                                $set('reason', null);
                                return;
                            }

                            $set('validationError', null);
                            $set('pqPlantError', null);
                            $set('pqLineError', null);
                            $set('pqWorkError', null);
                            $set('code', null);
                            $set('reason', null);
                        })
                    ->hint(fn ($get) => $get('pqWorkError') ? $get('pqWorkError') : null)
                    ->hintColor('danger'),
                Forms\Components\TextInput::make('code')
                    ->label('Code')
                    ->columnSpan(1)
                    ->required(),
                Forms\Components\TextInput::make('reason')
                    ->label('Reason')
                    ->columnSpan(['default' => 1, 'sm' => 2])
                    ->required(),
                Forms\Components\Hidden::make('created_by')
                    ->default(Filament::auth()->user()?->name),
            ])
                ->columns(['default' => 1, 'sm' => 3]),

            ]);
    }

    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')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('workGroupMaster.name')
                    ->label('WorkGroupName')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('code')
                    ->label('Code')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('reason')
                    ->label('Reason')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->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('Select Plant')
                        ->nullable()
                        // ->options(function () {
                        //     return Plant::pluck('name', 'id');
                        // })
                        ->options(function (callable $get) {
                            $userHas = Filament::auth()->user()->plant_id;
                            return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                        })
                        ->reactive()
                        ->afterStateUpdated(function ($state, callable $set, callable $get) {
                            $set('sap_msg_status', null);
                            $set('Line', null);
                            $set('created_by', null);
                        }),
                    Select::make('Line')
                        ->label('Select Line')
                        ->nullable()
                        ->options(function (callable $get) {
                            $plantId = $get('Plant');
                            if (!$plantId)
                            {
                                return [];
                            }

                            return Line::where('plant_id', $plantId)
                            ->pluck('name', 'id')
                            ->toArray();
                        })
                        ->reactive()
                        ->afterStateUpdated(function ($state, callable $set, callable $get) {
                            $set('created_by', null);
                        }),
                    Select::make('Code')
                        ->label('Code')
                        ->nullable()
                        ->options(function (callable $get) {
                            $plantId = $get('Plant');
                            $lineId = $get('Line');
                            if (!$plantId && !$lineId) {
                               return RejectReason::whereNotNull('code')->distinct() ->pluck('code', 'code');
                            }
                        })
                        ->reactive(),
                    Select::make('created_by')
                        ->label('Created By')
                        ->nullable()
                        ->options(function (callable $get) {
                            $plantId = $get('Plant');
                            $lineId = $get('Line');
                            if (!$plantId && !$lineId)
                            {
                                return RejectReason::whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                            }
                            else if ($plantId && !$lineId)
                            {
                                return RejectReason::where('plant_id', $plantId)->whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                            }
                            else
                            {
                                return RejectReason::where('plant_id', $plantId)->where('line_id', $lineId)->whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                            }
                        })
                        ->searchable()
                        ->reactive(),
                    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['Code']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['created_by'])) {
                    return $query->whereRaw('1 = 0');
                }

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

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

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

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

            })
            ->indicateUsing(function (array $data) {
                $indicators = [];

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

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

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

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

                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 Reject Reasons')
                    ->color('warning')
                    ->importer(RejectReasonImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import reject reason master');
                    }),
                ExportAction::make()
                    ->label('Export Reject Reasons')
                    ->color('warning')
                    ->exporter(RejectReasonExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export reject reason master');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListRejectReasons::route('/'),
            'create' => Pages\CreateRejectReason::route('/create'),
            'view' => Pages\ViewRejectReason::route('/{record}'),
            'edit' => Pages\EditRejectReason::route('/{record}/edit'),
        ];
    }

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