<?php

namespace App\Filament\Resources;

use App\Filament\Resources\ComputerResource\Pages;
use App\Models\Computer;
use App\Models\ComputerStatus;
use App\Models\ComputerType;
use App\Models\Enum\BookingStatusEnum;
use App\Models\Enum\RoleEnum;
use App\Models\Side;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Support\Enums\ActionSize;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Carbon\Carbon;

class ComputerResource extends Resource
{
    protected static ?string $model = Computer::class;

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

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

    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\TextInput::make('name')
                    ->label('Name')
                    ->required()
                    ->maxLength(255),

                Forms\Components\TextInput::make('mac_address')
                    ->label('MAC Address')
                    ->nullable()
                    ->maxLength(255),

                Forms\Components\TextInput::make('ip_address')
                    ->label('IP Address')
                    ->nullable()
                    ->ipv4()
                    ->maxLength(255),

                Forms\Components\Select::make('side_id')
                    ->label('Side (Library)')
                    ->searchable()
                    ->options(Side::all()->pluck('name', 'id'))
                    ->required(),

                Forms\Components\Select::make('computer_status_id')
                    ->label('Status')
                    ->searchable()
                    ->options(ComputerStatus::all()->pluck('name', 'id'))
                    ->required(),

                Forms\Components\Select::make('computer_type_id')
                    ->label('Computer Type')
                    ->searchable()
                    ->options(ComputerType::all()->pluck('name', 'id'))
                    ->required(),

                Forms\Components\TextInput::make('current_user_id')
                    ->label('Current User ID')
                    ->nullable()
                    ->maxLength(255)
                    ->numeric(),

                Forms\Components\DateTimePicker::make('reserved_until')
                    ->label('Reserved Until')
                    ->nullable(),

                Forms\Components\TextInput::make('browser_info')
                    ->label('Browser Info')
                    ->nullable()
                    ->maxLength(255),

                Forms\Components\TextInput::make('system_info')
                    ->label('System Info')
                    ->nullable()
                    ->maxLength(255),

                Forms\Components\TextInput::make('os_version')
                    ->label('OS Version')
                    ->nullable()
                    ->columnSpanFull()
                    ->maxLength(65535),

                Forms\Components\Checkbox::make('reserved')
                    ->label('Reserved')
                    ->default(false),


                Forms\Components\Checkbox::make('maintenance_required')
                    ->label('Maintenance Required')
                    ->default(false),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Computer Name')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('type.name')
                ->label('Computer Type')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\TextColumn::make('status.name')
                ->label('Status')
                    ->sortable()
                    ->searchable()
                    ->getStateUsing(fn ($record) => $record->status->name),

                Tables\Columns\TextColumn::make('side.name')
                ->label('Assigned Side')
                    ->sortable()
                    ->searchable(),

                Tables\Columns\IconColumn::make('available_noe')
                    ->boolean()
                    ->label('Available Now')
                    ->sortable()
                    ->getStateUsing(function ($record) {
                        $now = Carbon::now();
                        $activeBooking = $record->bookings()
                            ->where('start_time', '<=', $now)
                            ->where('end_time', '>=', $now)
                            ->where('booking_status_id', BookingStatusEnum::ID[BookingStatusEnum::CONFIRMED])
                            ->first();

                        return $activeBooking ? 'Yes' : 'No';
                    })
                    ->icon(function ($record) {
                        $now = Carbon::now();
                        $activeBooking = $record->bookings()
                            ->where('start_time', '<=', $now)
                            ->where('end_time', '>=', $now)
                            ->where('booking_status_id', BookingStatusEnum::ID[BookingStatusEnum::CONFIRMED])
                            ->first();

                        return $activeBooking ? 'heroicon-o-lock-closed' : 'heroicon-o-check';
                    })
                    ->color(function ($record) {
                        $now = Carbon::now();
                        $activeBooking = $record->bookings()
                            ->where('start_time', '<=', $now)
                            ->where('end_time', '>=', $now)
                            ->where('booking_status_id', BookingStatusEnum::ID[BookingStatusEnum::CONFIRMED])
                            ->first();

                        return $activeBooking ? 'danger' : 'success';
                    })
                    ->tooltip(function ($record) {
                        $now = Carbon::now();
                        $activeBooking = $record->bookings()
                            ->where('start_time', '<=', $now)
                            ->where('end_time', '>=', $now)
                            ->where('booking_status_id', BookingStatusEnum::ID[BookingStatusEnum::CONFIRMED])
                            ->first();

                        return $activeBooking ? 'Terminal Reserved' : 'Terminal Available';
                    }),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('computer_type_id')
                    ->label('Computer Type')
                    ->options(ComputerType::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select Computer Type'),

                Tables\Filters\SelectFilter::make('computer_status_id')
                    ->label('Status')
                    ->options(ComputerStatus::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select Status'),

                Tables\Filters\SelectFilter::make('side_id')
                    ->label('Side (Library)')
                    ->options(Side::all()->pluck('name', 'id')->toArray())
                    ->searchable()
                    ->placeholder('Select Side (Library)'),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\EditAction::make(),

                    Tables\Actions\Action::make('apply_controls')
                        ->label('Apply Access Control')
                        ->icon('heroicon-s-cog')
                        ->url(fn ($record) => ""/*route('terminal.apply-controls', $record)*/) // Redirige a la página de aplicar controles
                        ->color('warning'),

                    Tables\Actions\Action::make('go_to_side')
                        ->label('Go to Side (Library)')
                        ->icon('heroicon-o-map-pin')
                        ->url(fn ($record) => "/admin/sides?tableSearch=". $record->side->name)
                        ->color('success'),

                    Tables\Actions\Action::make('go_to_bookings')
                        ->label('Go to Bookings')
                        ->icon('heroicon-o-calendar-date-range')
                        ->url(fn ($record) => "/admin/bookings?tableFilters[computer_id][value]=". $record->id)
                        ->color('danger'),
                ])
                ->label('Actions')
                ->icon('heroicon-m-ellipsis-vertical')
                ->size(ActionSize::Small)
                ->color('primary')
                ->button()
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

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