<?php

namespace App\Filament\Resources;

use App\Filament\Exports\CharacteristicApproverMasterExporter;
use App\Filament\Imports\CharacteristicApproverMasterImporter;
use App\Filament\Resources\CharacteristicApproverMasterResource\Pages;
use App\Models\CharacteristicApproverMaster;
use App\Models\Machine;
use App\Models\Plant;
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\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;

class CharacteristicApproverMasterResource extends Resource
{
    protected static ?string $model = CharacteristicApproverMaster::class;

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

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

    protected static ?int $navigationSort = 2;

    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')
                            ->columnSpan(1)
                            ->reactive()
                            ->searchable()
                            ->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();
                            })
                            ->required()
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : optional(CharacteristicApproverMaster::latest()->first())->plant_id ?? null;
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('machine_id', null);
                                $set('machine_name', null);
                                $set('approver_type', null);
                                $set('characteristic_field', null);
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\Select::make('machine_id')
                            ->label('Work Center')
                            ->columnSpan(1)
                            // ->relationship('machine', 'name')
                            ->reactive()
                            ->searchable()
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    return [];
                                }

                                return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                            })
                            ->required()
                            ->default(function () {
                                return optional(CharacteristicApproverMaster::latest()->first())->machine_id ?? null;
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('machine_name', null);
                                $set('approver_type', null);
                                $set('characteristic_field', null);
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('machine_name')
                            ->label('Machine Name')
                            ->columnSpan(1)
                            ->reactive()
                            ->required()
                            ->minLength(5)
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : optional(CharacteristicApproverMaster::latest()->first())->machine_name ?? null;
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                if (! $state) {
                                    $set('approver_type', null);
                                    $set('characteristic_field', null);
                                }
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\Select::make('approver_type')
                            ->label('Approver Type')
                            ->columnSpan(1)
                            ->reactive()
                            ->nullable()
                            ->searchable()
                            ->required()
                            ->options(function (callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                $machineId = $get('machine_id');
                                $machineName = $get('machine_name');

                                if (! $plantId || ! $machineId || ! $machineName) {
                                    $set('characteristic_field', null);

                                    return [];
                                }

                                return [
                                    'Characteristic' => 'Characteristic',
                                    'Quality' => 'Quality',
                                ];
                            })
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : 'Characteristic';
                                // return optional(CharacteristicApproverMaster::latest()->first())->approver_type ?? null;
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('characteristic_field', 'NIL');
                                $set('updated_by', Filament::auth()->user()?->name);
                            }),
                        Forms\Components\TextInput::make('characteristic_field')
                            ->label('Master Characteristic Field')
                            ->columnSpan(4)
                            ->reactive()
                            ->required()
                            ->minLength(1)
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? null : 'NIL';
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                if (strtolower($state) == 'nil' || $state == '' || $state == null) {
                                    $set('characteristic_field', 'NIL');
                                }
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->rule(function (callable $get) {
                                return Rule::unique('characteristic_approver_masters', 'characteristic_field')
                                    ->where('plant_id', $get('plant_id'))
                                    ->where('machine_id', $get('machine_id'))
                                    ->where('approver_type', trim($get('approver_type')))
                                    ->where('machine_name', trim($get('machine_name')))
                                    ->ignore($get('id'));
                            }),
                        Section::make('Approver - 1')
                            // ->description('Prevent abuse by limiting the number of requests per period')
                            ->columnSpan(['default' => 2, 'sm' => 4])
                            ->schema([
                                Forms\Components\TextInput::make('name1')
                                    ->label('Name')
                                    ->reactive()
                                    ->required()
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                                Forms\Components\TextInput::make('mail1')
                                    ->label('Mail ID')
                                    ->columnSpan(['default' => 1, 'sm' => 2])
                                    ->reactive()
                                    ->required()
                                    ->suffixIcon('heroicon-m-envelope')
                                    ->suffixIconColor('primary')
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                                Forms\Components\TextInput::make('duration1')
                                    ->label('Duration (HH.MM)')
                                    ->reactive()
                                    ->required()
                                    ->minLength(4)
                                    ->maxLength(5)
                                    ->regex('/^([0-9]|0[0-9]|1[0-9]|2[0-3])\.(0[0-9]|[1-5][0-9])$/')
                                    ->validationMessages([
                                        // 'regex' => 'Duration must be 4 digits in HH.MM format (e.g., 12.30, 23.59). Hours: 00-23, Minutes: 00-59.',
                                        'regex' => 'Duration must be HH.MM format (example: 00.00 - 23.59)',
                                        // 'length' => 'Duration must be exactly 5 characters',
                                    ])
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                            ])
                            ->collapsed()// collapsible()
                            ->columns(['default' => 1, 'sm' => 4]),
                        Section::make('Approver - 2')
                            ->columnSpan(['default' => 2, 'sm' => 4])
                            ->schema([
                                Forms\Components\TextInput::make('name2')
                                    ->label('Name')
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                                Forms\Components\TextInput::make('mail2')
                                    ->label('Mail ID')
                                    ->columnSpan(['default' => 1, 'sm' => 2])
                                    ->reactive()
                                    ->suffixIcon('heroicon-m-envelope')
                                    ->suffixIconColor('primary')
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                                Forms\Components\TextInput::make('duration2')
                                    ->label('Duration (HH.MM)')
                                    ->reactive()
                                    ->minLength(4)
                                    ->maxLength(5)
                                    ->regex('/^([0-9]|0[0-9]|1[0-9]|2[0-3])\.(0[0-9]|[1-5][0-9])$/')
                                    ->validationMessages([
                                        'regex' => 'Duration must be HH.MM format (example: 00.00 - 23.59)',
                                    ])
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                            ])
                            ->collapsed()// collapsible()
                            ->columns(['default' => 1, 'sm' => 4]),
                        Section::make('Approver - 3')
                            ->columnSpan(['default' => 2, 'sm' => 4])
                            ->schema([
                                Forms\Components\TextInput::make('name3')
                                    ->label('Name')
                                    ->reactive()
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                                Forms\Components\TextInput::make('mail3')
                                    ->label('Mail ID')
                                    ->columnSpan(['default' => 1, 'sm' => 2])
                                    ->reactive()
                                    ->suffixIcon('heroicon-m-envelope')
                                    ->suffixIconColor('primary')
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                                Forms\Components\TextInput::make('duration3')
                                    ->label('Duration (HH.MM)')
                                    ->reactive()
                                    ->minLength(4)
                                    ->maxLength(5)
                                    ->regex('/^([0-9]|0[0-9]|1[0-9]|2[0-3])\.(0[0-9]|[1-5][0-9])$/')
                                    ->validationMessages([
                                        'regex' => 'Duration must be HH.MM format (example: 00.00 - 23.59)',
                                    ])
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        $set('updated_by', Filament::auth()->user()?->name);
                                    }),
                            ])
                            ->collapsed()// collapsible()
                            ->columns(['default' => 1, 'sm' => 4]),
                        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(),
                    ])
                    ->columns(['default' => 1, 'sm' => 4]),
            ]);
    }

    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')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('approver_type')
                    ->label('Approver Type')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine_name')
                    ->label('Machine Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristic_field')
                    ->label('Master Characteristic Field')
                    ->alignCenter()
                    ->searchable()
                    ->formatStateUsing(fn (string $state): string => strtoupper(__($state)))
                    ->extraAttributes(['class' => 'uppercase'])
                    ->sortable(),
                Tables\Columns\TextColumn::make('name1')
                    ->label('Approver Name 1')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('mail1')
                    ->label('E-Mail 1')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('duration1')
                    ->label('Duration 1 (Hour.Minute)')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name2')
                    ->label('Approver Name 2')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('mail2')
                    ->label('E-Mail 2')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('duration2')
                    ->label('Duration 2 (Hour.Minute)')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name3')
                    ->label('Approver Name 3')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('mail3')
                    ->label('E-Mail 3')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('duration3')
                    ->label('Duration 3 (Hour.Minute)')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->searchable()
                    ->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')
                    ->dateTime()
                    ->alignCenter()
                    ->searchable()
                    ->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('characteristicApproverMaster', 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('aufnr', 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('characteristicApproverMaster', 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);
                            }),
                        Select::make('approver_type')
                            ->label('Approver Type')
                            ->options([
                                'Characteristic' => 'Characteristic',
                                'Quality' => 'Quality',
                            ])
                            ->placeholder('Select Type')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('name1', null);
                                $set('name2', null);
                                $set('name3', null);
                            }),
                        TextInput::make('machine_name')
                            ->label('Machine Name')
                            ->placeholder('Enter Machine Name'),
                        TextInput::make('characteristic_field')
                            ->label('Characteristic Field')
                            ->placeholder('Enter Characteristic Field'),
                        TextInput::make('name1')
                            ->label('Approver Name 1')
                            ->placeholder('Enter Approver Name 2')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('name2', null);
                                $set('name3', null);
                            }),
                        TextInput::make('name2')
                            ->label('Approver Name 2')
                            ->placeholder('Enter Approver Name 2')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('name3', null);
                            }),
                        TextInput::make('name3')
                            ->label('Approver Name 3')
                            ->placeholder('Enter Approver Name 2'),
                        DateTimePicker::make(name: '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) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['machine']) && empty($data['machine_name']) && empty($data['characteristic_field']) && empty($data['approver_type']) && empty($data['name1']) && empty($data['name2']) && empty($data['name3']) && empty($data['created_from']) && empty($data['created_to'])) {
                            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['characteristic_field'])) {
                            $query->where('characteristic_field', 'like', '%'.$data['characteristic_field'].'%');
                        }

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

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

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

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

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

                        if (! empty($data['created_to'])) {
                            $query->where('created_at', '<=', $data['created_to']);
                        }
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

                        if (! empty($data['Plant'])) {
                            $indicators[] = 'Plant 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['characteristic_field'])) {
                            $indicators[] = 'Characteristic Field: '.$data['characteristic_field'];
                        }

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

                        if (! empty($data['name1'])) {
                            $indicators[] = 'Approver Name 1: '.$data['name1'];
                        }

                        if (! empty($data['name2'])) {
                            $indicators[] = 'Approver Name 2: '.$data['name2'];
                        }

                        if (! empty($data['name3'])) {
                            $indicators[] = 'Approver Name 3: '.$data['name3'];
                        }

                        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 Characteristics Approver Master')
                    ->color('warning')
                    ->importer(CharacteristicApproverMasterImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import characteristic approver master');
                    }),
                ExportAction::make()
                    ->label('Export Characteristics Approver Master')
                    ->color('warning')
                    ->exporter(CharacteristicApproverMasterExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export characteristic approver master');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCharacteristicApproverMasters::route('/'),
            'create' => Pages\CreateCharacteristicApproverMaster::route('/create'),
            'view' => Pages\ViewCharacteristicApproverMaster::route('/{record}'),
            'edit' => Pages\EditCharacteristicApproverMaster::route('/{record}/edit'),
        ];
    }

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