<?php

namespace App\Filament\Resources\Devices\Tables;

use App\Enums\DeviceType;
use App\Enums\Platform;
use App\Enums\SystemRole;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class DevicesTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('serial_number')->searchable()->sortable(),
                TextColumn::make('type')->searchable()->sortable()->formatStateUsing(fn ($state) => DeviceType::from($state)->label()),
                TextColumn::make('platform')->searchable()->sortable()->formatStateUsing(fn ($state) => Platform::from($state)->label()),
                ToggleColumn::make('is_active'),
                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->formatStateUsing(function ($state){
                        return $state->diffForHumans();
                    })
            ])
            ->filters([
                SelectFilter::make('type')->options(DeviceType::options()),
                SelectFilter::make('platform')->options(Platform::options())
            ])
            ->recordActions([
                Action::make('qr_code')
                    ->label('QR Code')
                    ->icon('mdi-qrcode-scan')
                    ->modalHeading(fn ($record) => "Device: {$record->serial_number}")
                    ->modalContent(function ($record) {
                        $url = route('devices.link', $record->uuid);
                        $qrCodeSvg = QrCode::format('svg')->size(200)->generate($url);

                        return view('filament.actions.qr-code-modal', [
                            'qrCodeSvg' => $qrCodeSvg,
                            'serial' => $record->serial_number,
                        ]);
                    })
                    ->modalWidth('sm')->modalActions([]),
                Action::make('setup')
                    ->label('Setup')
                    ->icon('heroicon-o-cog')
                    ->url(fn ($record) => route('filament.'.((auth()->user()->hasRole(SystemRole::SUPER_ADMIN))?"admin":"app").'.resources.devices.setup', $record))
                    ->openUrlInNewTab(false),
                EditAction::make(),
                DeleteAction::make()
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }
}
