<?php

namespace App\Livewire\Admin;

use App\Services\FlashMessageService;
use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Permission\Models\Role;

class RoleManagement extends Component
{
    use WithPagination;

    public $search = '';
    public $sortField = 'name';
    public $sortDirection = 'asc';

    public function delete($roleId)
    {
        // Check permission
        if (!auth()->user()->can('roles.delete')) {
            FlashMessageService::insufficientPermissions();
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'error', 'You do not have permission to delete roles.', 'Insufficient Permissions', 8000);
            
            return;
        }

        try {
            $role = Role::findOrFail($roleId);
            
            // Prevent deletion of Owner role
            if ($role->name === 'Owner') {
                FlashMessageService::error('Cannot delete the Owner role!', 'Protected Role');
                
                // Dispatch flash message event
                $this->dispatch('flashMessage', 'error', 'Cannot delete the Owner role!', 'Protected Role', 8000);
                
                return;
            }
            
            // Check if role has users
            if ($role->users()->count() > 0) {
                FlashMessageService::error('Cannot delete role that has users assigned. Please reassign users first.', 'Role In Use');
                
                // Dispatch flash message event
                $this->dispatch('flashMessage', 'error', 'Cannot delete role that has users assigned. Please reassign users first.', 'Role In Use', 8000);
                
                return;
            }
            
            $role->delete();
            FlashMessageService::success('Role deleted successfully!', 'Success');
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'success', 'Role deleted successfully!', 'Success', 5000);
            
        } catch (\Exception $e) {
            FlashMessageService::error('Failed to delete role. Please try again.', 'Error');
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'error', 'Failed to delete role. Please try again.', 'Error', 8000);
            
            \Log::error('Role deletion error: ' . $e->getMessage());
        }
    }

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        
        $this->sortField = $field;
    }

    public function render()
    {
        $query = Role::query()
            ->when($this->search, function ($query) {
                $query->where('name', 'like', '%' . $this->search . '%');
            })
            ->orderBy($this->sortField, $this->sortDirection);

        $roles = $query->paginate(10);

        return view('livewire.admin.role-management', [
            'roles' => $roles
        ]);
    }
}
