<?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 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) {
            $this->role = $role;
            $this->editing = true;
            $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();

        try {
            $data = [
                'name' => $this->name,
                'name_ar' => $this->name_ar,
                'slug' => $this->slug,
                'level' => $this->level,
                'description' => $this->description ?: null,
                'is_system' => false,
            ];

            if ($this->editing) {
                if ($this->role->is_system) {
                    session()->flash('error', 'لا يمكن تعديل دور النظام');
                    return;
                }
                $this->role->update($data);
                $role = $this->role;
            } else {
                $data['academy_id'] = app('current_academy')->id;
                $role = Role::create($data);
            }

            // Sync permissions with default 'academy' scope
            $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,
        ]);
    }
}
