<?php

namespace App\Filament\Resources;

use App\Filament\Exports\CheckPointTimeExporter;
use App\Filament\Imports\CheckPointTimeImporter;
use App\Filament\Resources\CheckPointTimeResource\Pages;
use App\Filament\Resources\CheckPointTimeResource\RelationManagers;
use App\Models\CheckPointName;
use App\Models\CheckPointTime;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
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\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Validation\Rule;

class CheckPointTimeResource extends Resource
{
    protected static ?string $model = CheckPointTime::class;

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

    protected static ?string $navigationGroup = 'Master Entries';

    protected static ?int $navigationSort = 16;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->relationship('plant', 'name')
                    ->required()
                    ->reactive()
                    ->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();
                    })
                    ->default(function () {
                        return optional(CheckPointTime::where('created_by', Filament::auth()->user()?->name)->latest()->first())->plant_id;
                    })
                    ->disabled(fn (Get $get) => !empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        if (!$plantId) {
                            $set('cPtPlantError', 'Please select a plant first.');
                            return;
                        }
                        else
                        {
                            $set('cPtPlantError', null);
                            $set('created_by', Filament::auth()->user()?->name);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('cPtPlantError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('cPtPlantError') ? $get('cPtPlantError') : null)
                    ->hintColor('danger'),
                Forms\Components\TextInput::make('sequence_number')
                    ->label('Sequence Number')
                    ->required()
                    ->reactive()
                    ->integer()
                    ->minValue(1)
                    ->default(1)
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $set('created_by', Filament::auth()->user()?->name);
                    })
                    ->rule(function (callable $get) {
                        return Rule::unique('check_point_times', 'sequence_number')
                        ->where('plant_id', $get('plant_id'))
                        ->ignore($get('id'));
                        //->where('check_point1_id', $get('check_point1_id'))
                        //->where('check_point2_id', $get('check_point2_id'))
                    }),
                Forms\Components\Select::make('check_point1_id')
                    ->label('Check Point Name 1')
                    // ->relationship('checkPointNames', 'name')
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (!$plantId) {
                            return [];
                        }

                        return CheckPointName::where('plant_id', $plantId)
                            ->pluck('name', 'id')
                            ->toArray();
                    })
                    ->required()
                    ->reactive()
                    ->default(function () {
                        return optional(CheckPointTime::where('created_by', Filament::auth()->user()?->name)->latest()->first())->check_point1_id;
                    })
                    ->disabled(fn (Get $get) => !empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $checkPoint1 = $get('check_point1_id');
                        $checkPoint2 = $get('check_point2_id');
                        if (!$checkPoint1) {
                            $set('cPtCheckPoint1Error', 'Please select a check point 1 first.');
                            return;
                        }
                        else
                        {
                            if ($checkPoint2 && $checkPoint1 == $checkPoint2) {
                                $set('cPtCheckPoint1Error', 'Duplicate check point 2 found.');
                                $set('check_point2_id', null);
                                return;
                            }
                            $set('cPtCheckPoint1Error', null);
                            $set('cPtCheckPoint2Error', null);
                            $set('created_by', Filament::auth()->user()?->name);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('cPtCheckPoint1Error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('cPtCheckPoint1Error') ? $get('cPtCheckPoint1Error') : null)
                    ->hintColor('danger'),
                Forms\Components\Select::make('check_point2_id')
                    ->label('Check Point Name 2')
                    // ->relationship('checkPointNames', 'name')
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (!$plantId) {
                            return [];
                        }

                        return CheckPointName::where('plant_id', $plantId)
                            ->pluck('name', 'id')
                            ->toArray();
                    })
                    ->required()
                    ->reactive()
                    ->default(function () {
                        return optional(CheckPointTime::where('created_by', Filament::auth()->user()?->name)->latest()->first())->check_point2_id;
                    })
                    ->disabled(fn (Get $get) => !empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $checkPoint1 = $get('check_point1_id');
                        $checkPoint2 = $get('check_point2_id');
                        if (!$checkPoint2) {
                            $set('cPtCheckPoint2Error', 'Please select a check point 2 first.');
                            return;
                        }
                        else
                        {
                            if ($checkPoint1 && $checkPoint1 == $checkPoint2) {
                                $set('cPtCheckPoint2Error', 'Duplicate check point 2 found.');
                                $set('check_point2_id', null);
                                return;
                            }
                            $set('cPtCheckPoint1Error', null);
                            $set('cPtCheckPoint2Error', null);
                            $set('created_by', Filament::auth()->user()?->name);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('cPtCheckPoint2Error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('cPtCheckPoint2Error') ? $get('cPtCheckPoint2Error') : null)
                    ->hintColor('danger')
                    ->rule(function (callable $get) {
                        return Rule::unique('check_point_times', 'check_point2_id')
                            ->where('check_point1_id', $get('check_point1_id'))
                            ->where('plant_id', $get('plant_id'))
                            ->ignore($get('id'));
                    }),
                Forms\Components\TextInput::make('time_lapse')
                    ->label('Time Lapse (in minutes)')
                    ->required()
                    ->integer()
                    ->minValue(1)
                    ->default(1)
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $timeLapse = $state;
                        $timeLapseCushioning = $get('time_lapse_cushioning');
                        if (!$timeLapse) {
                            $set('cPtTimeLapseError', 'Please enter a valid time lapse!');
                            $set('time_lapse_cushioning', null);
                            $set('min_cushioning', null);
                            $set('max_cushioning', null);
                            return;
                        }
                        elseif(!$timeLapseCushioning)
                        {
                            // $set('cPtTimeLapseError', 'Please enter a valid time lapse cushioning!');
                            $set('time_lapse_cushioning', 1);
                            $set('cPtTimeLapseError', null);
                            $set('min_cushioning', $timeLapse - 1);
                            $set('max_cushioning', $timeLapse + 1);
                            $set('created_by', Filament::auth()->user()?->name);
                            return;
                        }
                        elseif ($timeLapseCushioning > $timeLapse) {
                            $set('cPtTimeLapseError', 'Must be greater than or equal to time lapse cushioning!');
                            $set('time_lapse_cushioning', null);
                            $set('min_cushioning', null);
                            $set('max_cushioning', null);
                            return;
                        }
                        else
                        {
                            $set('cPtTimeLapseError', null);
                            $set('cPtTimeLapseCushError', null);
                            $set('min_cushioning', $timeLapse - $timeLapseCushioning);
                            $set('max_cushioning', $timeLapse + $timeLapseCushioning);
                            $set('created_by', Filament::auth()->user()?->name);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('cPtTimeLapseError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('cPtTimeLapseError') ? $get('cPtTimeLapseError') : null)
                    ->hintColor('danger'),
                Forms\Components\TextInput::make('time_lapse_cushioning')
                    ->label('Time Lapse Cushioning (in minutes)')
                    ->required()
                    ->integer()
                    ->minValue(1)
                    ->default(1)
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $timeLapse = $get('time_lapse');
                        $timeLapseCushioning = $state;
                        if (!$timeLapse) {
                            $set('cPtTimeLapseCushError', 'Please enter a valid time lapse first.');
                            $set('time_lapse_cushioning', null);
                            $set('min_cushioning', null);
                            $set('max_cushioning', null);
                            return;
                        }
                        elseif(!$timeLapseCushioning)
                        {
                            // $set('cPtTimeLapseCushError', 'Please enter a valid time lapse cushioning!');
                            $set('time_lapse_cushioning', 1);
                            $set('cPtTimeLapseCushError', null);
                            $set('min_cushioning', $timeLapse - 1);
                            $set('max_cushioning', $timeLapse + 1);
                            $set('created_by', Filament::auth()->user()?->name);
                            return;
                        }
                        elseif ($timeLapseCushioning > $timeLapse) {
                            $set('cPtTimeLapseCushError', 'Must be less than or equal to time lapse!');
                            $set('time_lapse_cushioning', null);
                            $set('min_cushioning', null);
                            $set('max_cushioning', null);
                            return;
                        }
                        else
                        {
                            $set('cPtTimeLapseError', null);
                            $set('cPtTimeLapseCushError', null);
                            $set('min_cushioning', $timeLapse - $timeLapseCushioning);
                            $set('max_cushioning', $timeLapse + $timeLapseCushioning);
                            $set('created_by', Filament::auth()->user()?->name);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('cPtTimeLapseCushError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('cPtTimeLapseCushError') ? $get('cPtTimeLapseCushError') : null)
                    ->hintColor('danger'),
                Forms\Components\Hidden::make('min_cushioning')
                    ->default(0)
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $set('created_by', Filament::auth()->user()?->name);
                    })
                    ->required(),
                Forms\Components\Hidden::make('max_cushioning')
                    ->default(2)
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $set('created_by', Filament::auth()->user()?->name);
                    })
                    ->required(),
                Forms\Components\Hidden::make('created_by')
                    ->default(fn () => Filament::auth()->user()?->name)
                    ->required(),
                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $set('created_by', Filament::auth()->user()?->name);
                    })
                    ->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('id')
                //     ->label('ID')
                //     ->numeric()
                //     ->sortable(),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('checkPointNames1.name')
                    ->label('Check Point 1')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('checkPointNames2.name')
                    ->label('Check Point 2')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('sequence_number')
                    ->label('Sequence Number')
                    ->alignCenter()
                    ->searchable()
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('time_lapse')
                    ->label('Time Lapse')
                    ->alignCenter()
                    ->searchable()
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('time_lapse_cushioning')
                    ->label('Time Lapse Cushioning (±)')
                    ->alignCenter()
                    ->searchable()
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->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 Check Point Times')
                    ->color('warning')
                    ->importer(CheckPointTimeImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import check point time');
                    }),
                ExportAction::make()
                    ->label('Export Check Point Times')
                    ->color('warning')
                    ->exporter(CheckPointTimeExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export check point time');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListCheckPointTimes::route('/'),
            'create' => Pages\CreateCheckPointTime::route('/create'),
            'view' => Pages\ViewCheckPointTime::route('/{record}'),
            'edit' => Pages\EditCheckPointTime::route('/{record}/edit'),
        ];
    }

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