<?php

namespace App\Filament\Resources;

use App\Filament\Exports\VehicleEntryExporter;
use App\Filament\Imports\VehicleEntryImporter;
use App\Filament\Resources\VehicleEntryResource\Pages;
use App\Models\Item;
use App\Models\Plant;
use App\Models\VehicleEntry;
use Carbon\Carbon;
use Filament\Facades\Filament;
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\Tables\Filters\Filter;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;

class VehicleEntryResource extends Resource
{
    protected static ?string $model = VehicleEntry::class;

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

    protected static ?string $navigationGroup = 'Vehicle';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->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();
                    })
                    ->required(),
                Forms\Components\TextInput::make('uuid')
                    ->label('Uuid')
                    ->required(),
                Forms\Components\TextInput::make('vehicle_number')
                    ->label('Vehicle Number')
                    ->required(),
                Forms\Components\TextInput::make('boom_opened')
                    ->label('Boom Opened')
                    ->required(),
                Forms\Components\DateTimePicker::make('entry_time')
                    ->label('Entry Time')
                    ->required()
                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                        $exitTime = $get('exit_time');

                        if ($state && $exitTime) {
                            $duration = Carbon::parse($exitTime)
                                ->diff(Carbon::parse($state))
                                ->format('%H:%I:%S');

                            $set('duration', $duration);
                        }
                    }),
                Forms\Components\DateTimePicker::make('exit_time')
                    ->label('Exit Time')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $get, callable $set) {
                        $entryTime = $get('entry_time');

                        if ($state && $entryTime) {
                            $duration = Carbon::parse($state)
                                ->diff(Carbon::parse($entryTime))
                                ->format('%H:%I:%S');

                            $set('duration', $duration);
                        }
                    }),
                Forms\Components\TextInput::make('duration')
                    ->label('Duration')
                    ->readOnly()
                    ->required(),
                Forms\Components\TextInput::make('type')
                    ->label('Type')
                    ->required(),
                Forms\Components\Hidden::make('created_by')
                    ->label('Created By'),
                Forms\Components\Hidden::make('updated_by')
                    ->label('Updated By'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->alignCenter()
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                // Tables\Columns\TextColumn::make('uuid')
                //     ->label('UUID')
                //     ->alignCenter()
                //     ->sortable()
                //     ->searchable(),
                Tables\Columns\TextColumn::make('vehicle_number')
                    ->label('Vehicle Number')
                    ->alignCenter()
                    ->sortable()
                    ->searchable()
                    ->formatStateUsing(fn ($state) => strtoupper($state)),
                Tables\Columns\TextColumn::make('boom_opened')
                    ->label('Boom Opened')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('entry_time')
                    ->label('Entry Time')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('exit_time')
                    ->label('Exit Time')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('duration')
                    ->label('Duration')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('type')
                    ->label('Type')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->searchable()
                    ->toggleable(isToggledHiddenByDefault: true),
                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()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        Select::make('Plant')
                            ->label('Search by Plant Name')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                if ($userHas && strlen($userHas) > 0) {
                                    return Plant::where('id', $userHas)->pluck('name', 'id')->toArray();
                                } else {
                                    return Plant::whereHas('vehicleEntries', 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('vehicle_number', null);
                            }),
                        TextInput::make('vehicle_number')
                            ->label('Vehicle Number')
                            ->reactive()
                            ->placeholder('Enter Vehicle Number')
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Rework', null);
                            }),
                        DateTimePicker::make('created_from')
                            ->label('Created From')
                            ->placeholder('Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('created_to')
                            ->label('Created To')
                            ->placeholder('Select To DateTime')
                            ->reactive()
                            ->native(false),
                    ])
                    ->query(function ($query, array $data) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['vehicle_number']) && 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['vehicle_number'])) {
                            $query->where('vehicle_number', 'like', '%'.$data['vehicle_number'].'%');
                        }

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

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

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

                        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(VehicleEntryImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import vehicle entry');
                    }),
                ExportAction::make()
                    ->exporter(VehicleEntryExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export vehicle entry');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListVehicleEntries::route('/'),
            'create' => Pages\CreateVehicleEntry::route('/create'),
            'view' => Pages\ViewVehicleEntry::route('/{record}'),
            'edit' => Pages\EditVehicleEntry::route('/{record}/edit'),
        ];
    }

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