<?php

namespace App\Livewire;

use App\Models\User;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Permission\Models\Role;
use Livewire\Attributes\On;
use Spatie\Permission\Models\Permission;

class RolesComponent extends Component
{
    use LivewireAlert;
    use WithPagination;

    //============================================ Variables
    public string $name = '';
    public string $search = '';
    public string $role = '';
    public int $method = 1;

    public  $user_info;
    public  $permisos;
    public $rol_seleccionado;
    public $PermisosSeleccionados = [];
    //============================================ Modal
    public $isChecked = true;
    public string $modalTitle = 'Agregar Rol';
    public function cancel()
    {
        $this->reset('name');
        $this->setTitleAddRoleModal();
    }
    public function setTitleAddRoleModal()
    {
        $this->method = 1;
        $this->modalTitle = 'Agregar Rol';
    }
    public function setTitleEditRoleModal()
    {
        $this->method = 2;
        $this->modalTitle = "Editar role - ($this->name)";
    }



    //====================== Cambiar permisos de rol

    public function editPermisos(int $rol_id)
    {

        try {

            $this->rol_seleccionado = Role::findById($rol_id);
            $permisos = Permission::orderBy('name')->get();
            $this->permisos = $permisos == null ? [] : $permisos;
            $this->PermisosSeleccionados = $this->rol_seleccionado->permissions->pluck('name')->toArray();
            // dd($this->PermisosSeleccionados);
            $this->fill([
                'modalTitle' => "Editar permisos - " . $this->rol_seleccionado->name,
                // 'detailData' => RemotaData::create($remota->toArray()),
                // 'detailData' => $remota,
                // 'user_info' => $user,
                'permisos' => $permisos
            ]);

            $this->dispatch('show-detail');
        } catch (ModelNotFoundException $e) {
            $this->alert('error', 'Usuario no encontrado.');
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG', $e));
            $this->alert('error', 'Error al mostrar el detalle del usuario.');
        }
    }
    public function syncPermisos()
    {
        try {

            $this->rol_seleccionado->syncPermissions($this->PermisosSeleccionados);
            $this->alert('success', 'Permisos de rol actualizados satisfactoriamente.', [
                'timer' => 5000,
            ]);
        } catch (Exception $e) {
            $this->alert('error', 'Error al actualizar los permisos del rol');
            throw_if(env('APP_DEBUG'), $e->getMessage());
        }
    }


    //============================================Busqueda
    public function updatingSearch()
    {
        $this->resetPage();
    }
    //============================================ Component
    public function save()
    {
        if ($this->method == 1) {
            $this->store();
        } else {
            $this->update();
        }
    }
    //====================== Store / Crear Rol
    private function store()
    {

        $this->validate(
            [
                'name' => 'required|unique:roles',
            ]
        );

        try {
            if (!Role::where('name', 'LIKE', '%' . trim(strtoupper($this->name)) . '%')->first()) {
                $role = Role::create([
                    'name' => trim(strtoupper($this->name)),
                    'guard_name' => 'web'
                ]);
                $this->alert('success', 'Rol creado satisfactoriamente.', [
                    'timer' => 5000,
                ]);
            } else {

                $this->alert('error', 'Error al crear el rol.');
            }

            $this->reset('name');
            $this->dispatch('hide-modal');
        } catch (Exception $e) {
            // if (isset($role)) {
            //     $role->forceDelete();
            // }
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al crear el rol.');
        }
    }
    //====================== Editar
    public function edit(int $id)
    {
        try {
            $role = Role::where('id', $id)->firstOrFail();
            $this->fill([
                'role' => $id,
                'name' => $role->name,
            ]);
            $this->method = 2;
        } catch (ModelNotFoundException $e) {
            $this->alert('error', 'Role no encontrado');
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al actualizar el Role');
        }
        $this->setTitleEditRoleModal();
        $this->dispatch('show-modal');
    }
    private function update()
    {
        try {
            $role = Role::where('id', $this->role)->firstOrFail();

            $this->validate(
                [
                    'name' => 'required|unique:roles',
                ]
            );

            $role->fill([
                'name' => $this->name,
            ]);

            $role->save();

            $this->alert('success', 'Role actualizado satisfactoriamente.', [
                'timer' => 5000,
            ]);
        } catch (ModelNotFoundException $e) {
            $this->alert('error', 'Role no encontrado');
        }
        $this->setTitleAddRoleModal();
        $this->cancel();
        $this->dispatch('hide-modal');
    }


    //====================== Eliminar
    public function confirmDelete(int $id)
    {
        $this->role = $id;
        $this->alert('warning', '¿Estas seguro?', [
            'position' => 'center',
            'text' => '¡Si elimina  este role no podra restaurarlo!',
            'showConfirmButton' => true,
            'confirmButtonText' => '¡Eliminar!',
            'showCancelButton' => true,
            'cancelButtonText' => 'Cancelar',
            'toast' => false,
            'onConfirmed' => 'confirmedDelete',
            'onDeny' => 'deniedDelete',
            'timer' => null,
            'reverseButtons' => true,
            'confirmButtonColor' => '#3085d6',
            'cancelButtonColor' => '#d33',
        ]);
    }
    #[On('confirmedDelete')]
    public function confirmedDelete()
    {
        try {

            $role = Role::findById($this->role);
            $hasUserAssigned = $role->users()->exists();
            $role_name = $role->name;
            if (!$role) {
                $this->alert('error', 'Error al eliminar el role', [
                    'text' => 'Rol no encontrado',

                ]);
            } else if (count($role->permissions) > 0) {
                $this->alert('error', 'Error al eliminar el role', [
                    'text' => 'El rol tiene algun permiso asignado',
                ]);
            } else if ($hasUserAssigned) {
                $this->alert('error', 'Error al eliminar el role', [
                    'text' => 'El rol tiene algun usuario asignado',
                ]);
            } else {
                DB::table('roles')->where('id', $this->role)->delete();
                // $role->delete();
                $this->alert('success', 'Exito al eliminar el role', [
                    'text' => $role_name,
                ]);
            }
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al eliminar el role');
        }
    }




    //====================== Render
    public function render()
    {
        $roles = Role::paginate(20);
        // $planes = Plan::search($this->search)->paginate(15);

        if (session()->has('message')) $this->alert(session('type'), session('message'));

        return view('livewire.roles-permisos.roles.roles-component', compact('roles'));
    }
}
