<?php

namespace App\Filament\Resources;

use App\Filament\Resources\RoleResource\Pages;
use Filament\Forms;
use Filament\Forms\Get;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;
use Spatie\Permission\Models\Role;



class RoleResource extends Resource
{
    protected static ?string $model = Role::class;

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

    protected static ?string $navigationLabel = 'Roles';
    
    public static function getModelLabel(): string
    {
        return 'Roles';
    }

    public static function getPluralModelLabel(): string
    {
        return 'Roles';
    }

    public static function getNavigationLabel(): string
    {
        return 'Roles';
    }

    public static function getModuleDescription(): string
    {
        return match (app()->getLocale()) {
            'en' => 'Manage roles and assign permissions to control access to modules and actions.',
            default => 'Administra roles y asigna permisos para controlar el acceso a módulos y acciones.',
        };
    }
    public static function canViewAny(): bool
    {
        return auth()->user()?->can('roles.view') ?? false;
    }

    public static function canCreate(): bool
    {
        return auth()->user()?->can('roles.create') ?? false;
    }

    public static function canEdit($record): bool
    {
        return auth()->user()?->can('roles.update') ?? false;
    }

    public static function canDelete($record): bool
    {
        return auth()->user()?->can('roles.delete') ?? false;
    }

    public static function canDeleteAny(): bool
    {
        return auth()->user()?->can('roles.delete') ?? false;
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->label('Nombre')
                    ->required()
                    ->maxLength(255)
                    ->unique(ignoreRecord: true),
                Forms\Components\Hidden::make('guard_name')
                    ->default('web'),
                Forms\Components\Placeholder::make('permissions_count')
                    ->label('Permisos asignados')
                    ->content(function (Get $get): HtmlString {
                        $count = count($get('permissions') ?? []);

                        return new HtmlString(
                             '<span class="text-primary-600 font-bold">'
                            . e((string) $count)
                            . '</span>',
                        );
                    })
                    ->visible(fn (string $context): bool => $context === 'edit'),
                Forms\Components\Select::make('permissions')
                    ->label('Permisos')
                    ->multiple()
                    ->searchable()
                    ->live()
                    ->preload()
                    ->relationship('permissions', 'name')
                    ->options(function (): array {
                        $groupLabels = [
                            'users' => 'Usuarios',
                            'roles' => 'Roles',
                            'modules' => 'Módulos',
                            'orders' => 'Órdenes',
                            'picking' => 'Picking',
                            'shipping' => 'Envíos',
                            'store_pickup' => 'Retiro en tienda',
                        ];

                        $grouped = [];

                        $permissions = \Spatie\Permission\Models\Permission::query()
                            ->orderBy('name')
                            ->get(['id', 'name']);

                        foreach ($permissions as $permission) {
                            $module = explode('.', $permission->name, 2)[0] ?? 'otros';
                            $group = $groupLabels[$module] ?? ucfirst($module);

                            $key = "permissions.{$permission->name}"; // ej: permissions.orders.view
                            $label = __($key);
                            if ($label === $key) {
                                $label = $permission->name;
                            }

                            $grouped[$group][$permission->id] = $label;
                        }

                        foreach ($grouped as $group => $options) {
                            asort($options); // ordena alfabéticamente dentro del grupo
                            $grouped[$group] = $options;
                        }

                        return $grouped;
                    }),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('Nombre')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('permissions_count')
                    ->label('Permisos')
                    ->counts('permissions')
                    ->sortable(),
                Tables\Columns\TextColumn::make('users_count')
                    ->label('Usuarios')
                    ->counts('users')
                    ->sortable(),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\DeleteBulkAction::make(),
            ]);
    }

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