<?php

namespace App\Livewire\Roles;

use App\Domain\Identity\Models\Permission;
use App\Domain\Identity\Models\Role;
use App\Domain\Identity\Services\RoleService;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إدارة الدور')]
class RoleForm extends Component
{
    public ?Role $role = null;
    public bool $editing = false;
    public bool $isSystem = false;

    public string $name = '';
    public string $name_ar = '';
    public string $slug = '';
    public int $level = 50;
    public string $description = '';
    public array $selectedPermissions = [];

    public function mount(?Role $role = null): void
    {
        if ($role && $role->exists) {
            $actor = auth()->user();
            if (!$actor->is_super_admin && $role->level >= ($actor->primaryRole?->level ?? 0)) {
                abort(403);
            }

            $this->role = $role;
            $this->editing = true;
            $this->isSystem = (bool) $role->is_system;
            $this->name = $role->name;
            $this->name_ar = $role->name_ar;
            $this->slug = $role->slug;
            $this->level = $role->level;
            $this->description = $role->description ?? '';
            $this->selectedPermissions = $role->permissions->pluck('id')->toArray();
        }
    }

    public function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'slug' => 'required|string|max:50',
            'level' => 'required|integer|min:0|max:99',
            'description' => 'nullable|string',
            'selectedPermissions' => 'array',
        ];
    }

    public function messages(): array
    {
        return [
            'name.required' => 'اسم الدور بالإنجليزية مطلوب',
            'name_ar.required' => 'اسم الدور بالعربية مطلوب',
            'slug.required' => 'المعرف مطلوب',
            'level.min' => 'المستوى يجب أن يكون 0 على الأقل',
            'level.max' => 'المستوى يجب ألا يتجاوز 99',
        ];
    }

    public function save(RoleService $roleService): void
    {
        $this->validate();

        $actor = auth()->user();

        try {
            if ($this->editing) {
                if (!$actor->is_super_admin && $this->role->level >= ($actor->primaryRole?->level ?? 0)) {
                    session()->flash('error', __('لا يمكنك تعديل دور بمستوى أعلى من مستواك'));
                    return;
                }

                if ($this->isSystem) {
                    $this->role->update([
                        'name_ar' => $this->name_ar,
                        'description' => $this->description ?: null,
                    ]);
                } else {
                    $this->role->update([
                        'name' => $this->name,
                        'name_ar' => $this->name_ar,
                        'slug' => $this->slug,
                        'level' => $this->level,
                        'description' => $this->description ?: null,
                    ]);
                }
                $role = $this->role;
            } else {
                $data = [
                    'name' => $this->name,
                    'name_ar' => $this->name_ar,
                    'slug' => $this->slug,
                    'level' => $this->level,
                    'description' => $this->description ?: null,
                    'academy_id' => app('current_academy')->id,
                    'is_system' => false,
                ];
                $role = Role::create($data);
            }

            $pivotData = collect($this->selectedPermissions)
                ->mapWithKeys(fn ($permId) => [$permId => ['scope' => 'academy']])
                ->toArray();
            $role->permissions()->sync($pivotData);

            session()->flash('success', $this->editing ? 'تم تحديث الدور بنجاح' : 'تم إنشاء الدور بنجاح');
            $this->redirect(route('roles.list'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $permissions = Permission::orderBy('module')->orderBy('action')->get();
        $grouped = $permissions->groupBy('module');

        return view('livewire.roles.role-form', [
            'permissionGroups' => $grouped,
        ]);
    }
}
