<?php

namespace App\Filament\Resources;

use App\Filament\Resources\RoleResource\Pages;
use App\Models\Permission;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

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

    protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-shield-check';

    protected static ?string $navigationLabel = 'الأدوار';

    protected static ?string $modelLabel = 'دور';

    protected static ?string $pluralModelLabel = 'الأدوار';

    protected static string | \UnitEnum | null $navigationGroup = 'إدارة الصلاحيات';

    protected static ?int $navigationSort = 1;

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make('معلومات الدور')
                    ->icon('heroicon-o-information-circle')
                    ->components([
                        TextInput::make('name')
                            ->label('اسم الدور')
                            ->required()
                            ->unique(ignoreRecord: true)
                            ->maxLength(255)
                            ->placeholder('مثال: مدير، مشرف، محرر')
                            ->helperText('اسم الدور الذي سيظهر في النظام')
                            ->columnSpanFull(),
                    ]),
                ...self::getPermissionSections(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('اسم الدور')
                    ->searchable()
                    ->sortable()
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'super_admin' => 'danger',
                        'admin' => 'warning',
                        'moderator' => 'info',
                        default => 'success',
                    }),
                Tables\Columns\TextColumn::make('permissions_count')
                    ->label('عدد الصلاحيات')
                    ->counts('permissions')
                    ->badge()
                    ->color('primary'),
                Tables\Columns\TextColumn::make('users_count')
                    ->label('عدد المستخدمين')
                    ->counts('users')
                    ->badge()
                    ->color('success'),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('تاريخ الإنشاء')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('name')
                    ->label('الدور')
                    ->options([
                        'super_admin' => 'مدير أعلى',
                        'admin' => 'مدير',
                        'moderator' => 'مشرف',
                    ])
                    ->placeholder('كل الأدوار')
                    ->searchable(),
            ])
            ->actions([
                EditAction::make(),
                DeleteAction::make()
                    ->before(function (Role $record) {
                        if ($record->name === 'super_admin') {
                            throw new \Exception('لا يمكن حذف دور المدير الأعلى');
                        }
                    }),
            ])
            ->bulkActions([
                DeleteBulkAction::make(),
            ]);
    }

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

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

    protected static function getPermissionSections(): array
    {
        $categories = [
            'users' => ['label' => 'المستخدمين', 'prefix' => 'users'],
            'clients' => ['label' => 'العملاء', 'prefix' => 'clients'],
            'technicians' => ['label' => 'الفنيين', 'prefix' => 'technicians'],
            'services' => ['label' => 'الخدمات', 'prefix' => 'services'],
            'categories' => ['label' => 'الأقسام', 'prefix' => 'categories'],
            'orders' => ['label' => 'الطلبات', 'prefix' => 'orders'],
            'packages' => ['label' => 'الباقات', 'prefix' => 'packages'],
            'subscriptions' => ['label' => 'الاشتراكات', 'prefix' => 'subscriptions'],
            'point_transactions' => ['label' => 'معاملات النقاط', 'prefix' => 'point_transactions'],
            'ratings' => ['label' => 'التقييمات', 'prefix' => 'ratings'],
            'additional_facilities' => ['label' => 'المرافق الإضافية', 'prefix' => 'additional_facilities'],
            'property_types' => ['label' => 'أنواع العقارات', 'prefix' => 'property_types'],
            'roles' => ['label' => 'الأدوار', 'prefix' => 'roles'],
            'permissions' => ['label' => 'الصلاحيات', 'prefix' => 'permissions'],
            'reports' => ['label' => 'التقارير', 'prefix' => 'reports'],
            'settings' => ['label' => 'الإعدادات', 'prefix' => 'settings'],
            'notifications' => ['label' => 'الإشعارات', 'prefix' => 'notifications'],
        ];

        $sections = [];

        foreach ($categories as $key => $category) {
            $permissions = Permission::where(function ($query) use ($category) {
                $query->where('name', 'like', '%_' . $category['prefix'] . '%')
                    ->orWhere('name', 'like', $category['prefix'] . '_%');
            })
            ->orderBy('name')
            ->get();

            if ($permissions->isEmpty()) {
                continue;
            }

            $permissionOptions = [];
            foreach ($permissions as $permission) {
                $permissionOptions[$permission->id] = $permission->name_ar ?: ($permission->name_en ?: $permission->name);
            }

            $permissionCount = count($permissionOptions);
            $icons = [
                'users' => 'heroicon-o-users',
                'clients' => 'heroicon-o-user-group',
                'technicians' => 'heroicon-o-wrench-screwdriver',
                'services' => 'heroicon-o-briefcase',
                'categories' => 'heroicon-o-folder',
                'orders' => 'heroicon-o-shopping-cart',
                'packages' => 'heroicon-o-gift',
                'subscriptions' => 'heroicon-o-credit-card',
                'point_transactions' => 'heroicon-o-sparkles',
                'ratings' => 'heroicon-o-star',
                'additional_facilities' => 'heroicon-o-building-office-2',
                'property_types' => 'heroicon-o-home',
                'roles' => 'heroicon-o-shield-check',
                'permissions' => 'heroicon-o-key',
                'reports' => 'heroicon-o-document-chart-bar',
                'settings' => 'heroicon-o-cog-6-tooth',
                'notifications' => 'heroicon-o-bell',
            ];
            
            $icon = $icons[$key] ?? 'heroicon-o-check-circle';
            
            $sections[] = Section::make($category['label'])
                ->icon($icon)
                ->description("إدارة صلاحيات {$category['label']} ({$permissionCount} صلاحية متاحة)")
                ->collapsible()
                ->collapsed()
                ->components([
                    CheckboxList::make('permissions_' . $key)
                        ->label('')
                        ->options($permissionOptions)
                        ->columns(3)
                        ->gridDirection('row')
                        ->searchable()
                        ->bulkToggleable()
                        ->default([])
                        ->helperText("اختر الصلاحيات المطلوبة لإدارة {$category['label']}")
                        ->columnSpanFull(),
                ]);
        }

        return $sections;
    }
}

