<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use App\Models\User;
use Filament\Infolists\Components\TextEntry;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;

/**
 * Ported from UserManagementUserController::show(), including the
 * per-permission provenance table (User::permissionSources()) used for
 * auditing why a user holds — or was denied — a given permission.
 */
class ViewUser extends ViewRecord
{
    protected static string $resource = UserResource::class;

    /**
     * @var array<int, array{roles: array<string, array<int, string>>, allow: array<int, string>, deny: array<int, string>, inherited: array<int, string>, effective: array<int, string>}>
     */
    protected array $permissionSourcesCache = [];

    /**
     * The four permission entries below each need this, and it runs several
     * queries internally — memoized per record so rendering the page costs
     * one computation instead of four.
     *
     * @return array{roles: array<string, array<int, string>>, allow: array<int, string>, deny: array<int, string>, inherited: array<int, string>, effective: array<int, string>}
     */
    protected function permissionSources(User $record): array
    {
        return $this->permissionSourcesCache[$record->getKey()] ??= $record->permissionSources();
    }

    public function infolist(Schema $schema): Schema
    {
        return $schema->components([
            Section::make()->schema([
                TextEntry::make('name'),
                TextEntry::make('email'),
                TextEntry::make('phone')->placeholder('—'),
                TextEntry::make('status')
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => ucfirst($state))
                    ->color(fn (string $state): string => match ($state) {
                        User::STATUS_ACTIVE => 'success',
                        User::STATUS_SUSPENDED => 'danger',
                        User::STATUS_INACTIVE => 'gray',
                        default => 'gray',
                    }),
                TextEntry::make('last_login_at')->dateTime()->placeholder('Never'),
                TextEntry::make('roles.name')->label('Roles')->badge()->placeholder('—'),
                TextEntry::make('warehouses.name')->label('Warehouses')->badge()->placeholder('—'),
                TextEntry::make('tills.name')->label('Tills')->badge()->placeholder('—'),
            ])->columns(3),

            Section::make('Effective permissions')
                ->description('Every permission this user currently holds, and where it comes from. Inherited permissions follow the roles above — edit a role and they change here too. Pinned ones were set for this user specifically and stay put even if their roles change.')
                ->schema([
                    TextEntry::make('effective_permissions')
                        ->label('Effective')
                        ->state(fn (User $record): array => $this->permissionSources($record)['effective'])
                        ->listWithLineBreaks()
                        ->placeholder('None.'),
                    TextEntry::make('inherited_permissions')
                        ->label('Inherited from roles')
                        ->state(fn (User $record): array => $this->permissionSources($record)['inherited'])
                        ->listWithLineBreaks()
                        ->placeholder('None.'),
                    TextEntry::make('allow_overrides')
                        ->label('Pinned on (granted to this user only)')
                        ->badge()
                        ->color('warning')
                        ->state(fn (User $record): array => $this->permissionSources($record)['allow'])
                        ->listWithLineBreaks()
                        ->placeholder('None.'),
                    TextEntry::make('deny_overrides')
                        ->label('Pinned off (revoked from this user only)')
                        ->badge()
                        ->color('danger')
                        ->state(fn (User $record): array => $this->permissionSources($record)['deny'])
                        ->listWithLineBreaks()
                        ->placeholder('None.'),
                ])->columns(2),
        ]);
    }
}
