<?php

namespace App\Filament\Resources;

use App\Filament\Resources\VehicleEntryResource\Pages;
use App\Filament\Resources\VehicleEntryResource\RelationManagers;
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;

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

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

    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('vehicle_number')
                    ->label('Vehicle Number')
                    ->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('vehicle_number')
                    ->label('Vehicle Number')
                    ->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('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->dateTime()
                    ->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(),
                ]),
            ]);
    }

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