<?php

namespace App\Filament\Resources\UserResource\Pages;

use App\Filament\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\ViewRecord;
use Filament\Infolists;
use Filament\Infolists\Infolist;

class ViewUser extends ViewRecord
{
    protected static string $resource = UserResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\EditAction::make()
                ->label('编辑'),
        ];
    }

    public function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Infolists\Components\Section::make('基本信息')
                    ->schema([
                        Infolists\Components\TextEntry::make('name')
                            ->label('用户名称'),
                        Infolists\Components\TextEntry::make('email')
                            ->label('邮箱'),
                        Infolists\Components\TextEntry::make('created_at')
                            ->label('创建时间')
                            ->dateTime('Y-m-d H:i:s'),
                        Infolists\Components\TextEntry::make('updated_at')
                            ->label('更新时间')
                            ->dateTime('Y-m-d H:i:s'),
                    ])
                    ->columns(2),

                Infolists\Components\Section::make('角色信息')
                    ->schema([
                        Infolists\Components\TextEntry::make('roles.name')
                            ->label('已分配角色')
                            ->badge()
                            ->color(fn (string $state): string => match ($state) {
                                'super-admin' => 'danger',
                                'admin' => 'warning',
                                'user' => 'success',
                                default => 'gray',
                            })
                            ->formatStateUsing(fn (string $state): string => match ($state) {
                                'super-admin' => '超级管理员',
                                'admin' => '管理员',
                                'user' => '普通用户',
                                default => $state,
                            })
                            ->placeholder('未分配角色'),
                    ]),

                Infolists\Components\Section::make('分组信息')
                    ->schema([
                        Infolists\Components\TextEntry::make('groups.name')
                            ->label('所属分组')
                            ->badge()
                            ->placeholder('未加入任何分组'),
                    ]),

                Infolists\Components\Section::make('权限详情')
                    ->description('显示用户拥有的所有权限（包括角色权限和直接权限）')
                    ->schema([
                        Infolists\Components\TextEntry::make('all_permissions')
                            ->label('所有权限')
                            ->getStateUsing(function ($record) {
                                // 获取所有权限（角色权限 + 直接权限）
                                $permissions = $record->getAllPermissions();
                                
                                if ($permissions->isEmpty()) {
                                    return '该用户暂无权限';
                                }
                                
                                // 按模块分组
                                $grouped = $permissions->groupBy(function ($permission) {
                                    return explode('.', $permission->name)[0];
                                });
                                
                                $moduleNames = [
                                    'document' => '📄 文档管理',
                                    'system-setting' => '⚙️ 系统设置',
                                    'activity-log' => '📋 操作日志',
                                    'terminal' => '🖥️ 终端管理',
                                    'guide' => '📖 操作指引',
                                    'group' => '👥 分组管理',
                                    'user' => '👤 用户管理',
                                    'role' => '🛡️ 角色管理',
                                ];
                                
                                $actionNames = [
                                    'viewAny' => '查看列表',
                                    'view' => '查看详情',
                                    'create' => '创建',
                                    'update' => '编辑',
                                    'delete' => '删除',
                                    'download' => '下载',
                                    'export' => '导出',
                                    'sync' => '同步',
                                    'publish' => '发布',
                                    'archive' => '归档',
                                ];
                                
                                $result = [];
                                foreach ($grouped as $module => $perms) {
                                    $moduleName = $moduleNames[$module] ?? $module;
                                    $actions = $perms->map(function ($perm) use ($actionNames) {
                                        $action = explode('.', $perm->name)[1] ?? '';
                                        return $actionNames[$action] ?? $action;
                                    })->join('、');
                                    
                                    $result[] = "<strong>{$moduleName}</strong>：{$actions}";
                                }
                                
                                return implode('<br><br>', $result);
                            })
                            ->html()
                            ->columnSpanFull(),
                            
                        Infolists\Components\TextEntry::make('direct_permissions')
                            ->label('直接权限（仅显示直接分配的权限）')
                            ->getStateUsing(function ($record) {
                                $permissions = $record->permissions;
                                
                                if ($permissions->isEmpty()) {
                                    return '无直接权限';
                                }
                                
                                // 按模块分组
                                $grouped = $permissions->groupBy(function ($permission) {
                                    return explode('.', $permission->name)[0];
                                });
                                
                                $moduleNames = [
                                    'document' => '📄 文档管理',
                                    'system-setting' => '⚙️ 系统设置',
                                    'activity-log' => '📋 操作日志',
                                    'terminal' => '🖥️ 终端管理',
                                    'guide' => '📖 操作指引',
                                    'group' => '👥 分组管理',
                                    'user' => '👤 用户管理',
                                    'role' => '🛡️ 角色管理',
                                ];
                                
                                $actionNames = [
                                    'viewAny' => '查看列表',
                                    'view' => '查看详情',
                                    'create' => '创建',
                                    'update' => '编辑',
                                    'delete' => '删除',
                                    'download' => '下载',
                                    'export' => '导出',
                                    'sync' => '同步',
                                    'publish' => '发布',
                                    'archive' => '归档',
                                ];
                                
                                $result = [];
                                foreach ($grouped as $module => $perms) {
                                    $moduleName = $moduleNames[$module] ?? $module;
                                    $actions = $perms->map(function ($perm) use ($actionNames) {
                                        $action = explode('.', $perm->name)[1] ?? '';
                                        return $actionNames[$action] ?? $action;
                                    })->join('、');
                                    
                                    $result[] = "<strong>{$moduleName}</strong>：{$actions}";
                                }
                                
                                return implode('<br><br>', $result);
                            })
                            ->html()
                            ->columnSpanFull()
                            ->color('info'),
                    ]),
            ]);
    }
}
