<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserSessionResource\Pages;
use App\Filament\Resources\UserSessionResource\RelationManagers;
use App\Models\AccessControl;
use App\Models\Computer;
use App\Models\Enum\RoleEnum;
use App\Models\Enum\UserSessionStatusEnum;
use App\Models\SessionStatus;
use App\Models\User;
use App\Models\UserSession;
use App\Models\UserTypeRule;
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 Illuminate\Support\Facades\View;

class UserSessionResource extends Resource
{
    protected static ?string $model = UserSession::class;

    protected static ?string $navigationGroup = "User Management";

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

    public static function canViewAny(): bool
    {
        return auth()->user()->role_id !== RoleEnum::ID[RoleEnum::SIDE_USER];
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('side_id')
                    ->label('Side')
                    ->relationship('side', 'name')
                    ->required()
                    ->searchable(),

                Forms\Components\Select::make('computer_id')
                    ->label('Computer')
                    ->relationship('computer', 'name')
                    ->required()
                    ->searchable(),

                Forms\Components\Select::make('session_status_id')
                    ->label('Session Status')
                    ->relationship('sessionStatus', 'name')
                    ->required(),

                Forms\Components\Select::make('booking_id')
                    ->label('Booking')
                    ->relationship('booking', 'id')
                    ->required()
                    ->searchable(),

                Forms\Components\TimePicker::make('start_time')
                    ->label('Start Time')
                    ->required(),

                Forms\Components\TimePicker::make('end_time')
                    ->label('End Time')
                    ->required(),

                Forms\Components\TextInput::make('duration')
                    ->label('Duration (minutes)')
                    ->numeric()
                    ->required()
                    ->default(fn ($get) => $get('end_time') && $get('start_time')
                        ? now()->parse($get('end_time'))->diffInMinutes(now()->parse($get('start_time')))
                        : null),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make("booking.user.name")
                    ->label('User')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make("computer.name")
                    ->label('Assigned Computer')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make("start_time")
                    ->label('Start Time')
                    ->formatStateUsing(function ($record) {
                        return \Carbon\Carbon::parse($record->start_time)->format('d/m/Y H:i:s');
                    })
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make("end_time")
                    ->label('End Time')
                    ->formatStateUsing(function ($record) {
                        return \Carbon\Carbon::parse($record->end_time)->format('d/m/Y H:i:s');
                    })
                    ->searchable()
                    ->sortable(),

                Tables\Columns\TextColumn::make("sessionStatus.name")
                    ->label("Status")
                    ->searchable()
                    ->sortable()
                    ->formatStateUsing(function ($state) {
                        if (is_null($state)) {
                            return '<span class="text-gray-500">No Status</span>';
                        }

                        switch ($state) {
                            case 'Activa':
                                return '<span class="text-yellow-500">⏰ Active</span>';
                            case 'Completada':
                                return '<span class="text-green-500">✅ Completed</span>';
                            case 'Expirada':
                                return '<span class="text-orange-500">⚠️ Expired</span>';
                            case 'Cancelada':
                                return '<span class="text-red-500">❌ Cancelled</span>';
                            case 'Terminada':
                                return '<span class="text-green-500">✅ Finished</span>';
                            case 'Pendiente':
                                return '<span class="text-yellow-500">⏰ Pending</span>';
                            case 'Abortada':
                                return '<span class="text-red-500">❌ Aborted</span>';
                            default:
                                return '<span class="text-gray-500">Unknown</span>';
                        }
                    })
                    ->html(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('session_status_id')
                    ->label('Status')
                    ->options(SessionStatus::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select Session Status'),

                Tables\Filters\Filter::make('booking_user')
                    ->label('User')
                    ->form([
                        Forms\Components\Select::make("user_name")
                            ->label('User')
                            ->options(User::all()->pluck('name', 'id')->toArray())
                            ->searchable()
                            ->placeholder('Select User'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['user_name'] ?? null,
                                function (Builder $query, $userId) {
                                    $query->whereHas('booking.user', function (Builder $subQuery) use ($userId) {
                                        $subQuery->where('id', $userId);
                                    });
                                }
                            );
                    }),

                Tables\Filters\SelectFilter::make('computer_id')
                    ->label('Assigned Computer')
                    ->options(Computer::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select Assigned Computer'),

                Tables\Filters\Filter::make('id')
                    ->form([
                        Forms\Components\TextInput::make("id")
                            ->visible(false),
                    ])
                    ->query(function (Builder $query, array $data) {
                        if ($data["id"]) {
                            return $query->where('id', $data["id"]);
                        }
                        return $query;
                    }),
            ])
            ->actions([
                //Tables\Actions\EditAction::make(),

                Tables\Actions\Action::make('go_to_booking')
                    ->label('Go to Booking')
                    ->icon('heroicon-o-calendar-date-range')
                    ->url(fn ($record) => "/admin/bookings?tableFilters[id][id]=". $record->booking->id)
                    ->color('danger'),

                Tables\Actions\Action::make('finish_session')
                    ->label('Finish Session')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->action(function ($record) {
                        $record->update(['session_status_id' => UserSessionStatusEnum::ID[UserSessionStatusEnum::FINISHED]]);

                        session()->flash('success', 'User Session has been finished.');
                    })
                    ->requiresConfirmation()
                    ->modalHeading('Are you sure you want to finish this user session?')
                    ->modalSubmitActionLabel('Confirm')
                    ->modalDescription('Once finished, user session does not restored.')
                    ->visible(function ($record) {
                        return $record->session_status_id !== UserSessionStatusEnum::ID[UserSessionStatusEnum::FINISHED];
                    }),

                Tables\Actions\Action::make('view_controls_and_rules')
                    ->label('View Controls & Rules')
                    ->icon('heroicon-o-eye')
                    ->modalHeading('User Session Controls and Rules')
                    ->modalWidth('lg')
                    ->action(function (UserSession $record) {
                        return ['record' => $record,];
                    })
                    ->modalContent(function (UserSession $record) {
                        $user = $record->booking->user;
                        $userType = $user->userType;

                        $accessControls = AccessControl::where('user_type_id', $userType->id)->get();
                        $userTypeRules = UserTypeRule::where('user_type_id', $userType->id)->get();

                        return view('vendor.filament-panels.user-sessions.controls-rules', [
                            'accessControls' => $accessControls,
                            'userTypeRules' => $userTypeRules,
                        ]);
                    })
                    ->modalSubmitAction(false)
                    ->modalCancelAction(false),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    //Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUserSessions::route('/'),
            'create' => Pages\CreateUserSession::route('/create'),
            //'edit' => Pages\EditUserSession::route('/{record}/edit'),
        ];
    }
}
