<?php

namespace App\Livewire\Admin;

use Illuminate\Database\Eloquent\Builder;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RoleTable extends DataTableComponent
{
    protected $model = Role::class;

    private const PROTECTED_ROLES = ['Admin'];

    public function configure(): void
    {
        $this->setPrimaryKey('id')
            ->setDefaultSort('name', 'asc')
            ->setSortingPillsEnabled(false);
    }

    public function builder(): Builder
    {
        return Role::withCount(['permissions', 'users']);
    }

    public function columns(): array
    {
        return [
            Column::make(__('Name'), 'name')
                ->sortable()
                ->searchable()
                ->format(fn ($value, $row) => '<a href="'.route('admin.roles.show', $row->id).'" class="font-semibold text-primary hover:underline" wire:navigate>'.e($value).'</a>'
                    .(in_array($row->name, self::PROTECTED_ROLES, true) ? ' <span class="badge badge-ghost badge-xs">protegido</span>' : '')
                )
                ->html(),

            Column::make(__('Description'), 'description')
                ->sortable()
                ->searchable()
                ->format(fn ($value) => $value
                    ? '<span class="text-sm text-gray-500">'.e($value).'</span>'
                    : '<span class="text-gray-300">—</span>')
                ->html(),

            Column::make(__('Permissions'))
                ->label(fn ($row) => '<span class="badge badge-outline badge-sm">'.(int) $row->permissions_count.'</span>')
                ->html(),

            Column::make(__('Users'))
                ->label(fn ($row) => '<span class="badge badge-ghost badge-sm">'.(int) $row->users_count.'</span>')
                ->html(),

            Column::make(__('Actions'))
                ->label(function ($row) {
                    $show = route('admin.roles.show', $row->id);
                    $edit = route('admin.roles.edit', $row->id);
                    $eye = '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>';
                    $pencil = '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>';
                    $trash = '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>';

                    $html = '<div class="flex items-center gap-1">';
                    $html .= '<a href="'.$show.'" class="btn btn-xs btn-ghost" title="Ver" wire:navigate>'.$eye.'</a>';
                    $html .= '<a href="'.$edit.'" class="btn btn-xs btn-ghost text-info" title="Editar" wire:navigate>'.$pencil.'</a>';
                    if (! in_array($row->name, self::PROTECTED_ROLES, true)) {
                        $html .= '<button wire:click="deleteRole('.$row->id.')" wire:confirm="¿Eliminar el rol \''.e($row->name).'\'?" class="btn btn-xs btn-ghost text-error" title="Eliminar">'.$trash.'</button>';
                    }
                    $html .= '</div>';

                    return $html;
                })
                ->html(),
        ];
    }

    public function bulkActions(): array
    {
        return ['bulkDelete' => __('Delete selected')];
    }

    public function bulkDelete(): void
    {
        $roles = Role::whereIn('id', $this->selected)->get();
        foreach ($roles as $role) {
            if (in_array($role->name, self::PROTECTED_ROLES, true)) {
                continue;
            }
            $role->delete();
        }
        $this->clearSelected();
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        $this->dispatch('notify', __('Roles deleted'));
    }

    public function deleteRole(int $id): void
    {
        $role = Role::findOrFail($id);
        if (in_array($role->name, self::PROTECTED_ROLES, true)) {
            return;
        }
        $role->delete();
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        $this->dispatch('notify', __('Role deleted'));
    }
}
