<?php

namespace App\Livewire\User;

use App\Models\User;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Permission\Models\Role;

final class UserComponent extends Component
{
    use LivewireAlert;
    use WithPagination;

    //============================================ Variables
    #[Url]
    public string $search = '';
    public string $nombre = '';
    public string $email = '';
    public string $password = '';
    //===================== Min Variables
    public  $roles;
    public  $user_info;
    public $RolesSeleccionados = [];
    #[Locked]
    public string $user = '';
    #[Locked]
    public string $modalTitle = 'Agregar Usuario';



    //====================== Roles usuario
    public function editRoles(int $id)
    {

        try {

            $user = User::where('id', $id)->firstOrFail();
            $roles = Role::all();
            $this->RolesSeleccionados = $user->getRoleNames()->toArray();
            $this->fill([
                'modalTitle' => "Detalle del {$user->name}",
                // 'detailData' => RemotaData::create($remota->toArray()),
                // 'detailData' => $remota,
                'user_info' => $user,
                'roles' => $roles,
            ]);

            $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 syncRoles()
    {
        try {

            $this->user_info->syncRoles($this->RolesSeleccionados);
            $this->alert('success', 'Roles Actualizados satisfactoriamente.', [
                'timer' => 5000,
            ]);
        } catch (Exception $e) {
            $this->alert('error', 'Error Con roles encontrado');
            throw_if(env('APP_DEBUG'), $e->getMessage());
        }
    }
    //====================== Modal
    private function setTitleAddUserModal()
    {
        $this->modalTitle = 'Agregar Usuario';
    }

    private function setTitleEditUserModal()
    {
        $this->modalTitle = "Editar usuario ($this->nombre)";
    }
    public function cancel()
    {
        $this->reset('nombre', 'email', 'user', 'password');
        $this->setTitleAddUserModal();
    }

    //============================================Busqueda
    public function updatingSearch()
    {
        $this->resetPage();
    }

    //============================================ Component
    public function save()
    {

        if (! str()->isUuid($this->user)) {
            $this->store();
        } else {
            $this->update();
        }
    }
    //====================== Store / Crear Rol

    private function store()
    {

        $this->validate(
            [
                'nombre' => 'required',
                'email' => 'required|unique:users,email',
            ]
        );

        try {

            $user = User::create([
                'name' => $this->nombre,
                'email' => $this->email,
                'password' => Hash::make($this->password),
            ]);

            $this->reset('nombre', 'email', 'password');

            $this->alert('success', 'Usuario creado satisfactoriamente.', [
                'timer' => 5000,
            ]);
        } catch (Exception $e) {
            if (isset($user)) {
                $user->forceDelete();
            }
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al crear el usuario.');
        }
    }
    //====================== Editar

    public function edit(string $uuid)
    {
        try {
            $user = User::where('uuid', $uuid)->firstOrFail();
            $this->fill([
                'user' => $uuid,
                'nombre' => $user->name,
                'email' => $user->email,
            ]);
        } catch (ModelNotFoundException $e) {
            $this->alert('error', 'Usuario no encontrado');
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al actualizar al usuario');
        }
        $this->setTitleEditUserModal();
        $this->dispatch('show-modal');
    }
    private function update()
    {
        try {
            $user = User::where('uuid', $this->user)->firstOrFail();

            $this->validate(
                [
                    'nombre' => 'required',
                    'email' => ['required', Rule::unique('users', 'email')->ignore($user)],
                ]
            );

            if ($this->password != '') {
                $user->fill([
                    'nombre' => $this->nombre,
                    'email' => $this->email,
                    'password' => Hash::make($this->password),
                ]);
            } else {
                $user->fill([
                    'name' => $this->nombre,
                    'email' => $this->email,
                ]);
            }

            $user->save();

            $this->alert('success', 'Usuario actualizado satisfactoriamente.', [
                'timer' => 5000,
            ]);
        } catch (ModelNotFoundException $e) {
            $this->alert('error', 'Usuario no encontrado');
        }
        $this->setTitleAddUserModal();
        $this->cancel();
        $this->dispatch('hide-modal');
    }
    //====================== Eliminar
    public function getListeners()
    {
        return [
            'confirmedDelete',
            'deniedDelete',
        ];
    }
    public function confirmDelete(string $uuid)
    {
        $this->user = $uuid;
        $this->alert('warning', '¿Estas seguro?', [
            'position' => 'center',
            'text' => '¡Si elimina a este usuario 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 {
            $user = User::where('uuid', $this->user)->first();

            if ($user) {
                $user->delete();
                $this->alert(message: 'Usuario eliminado con exito');
            }
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al eliminar al usuario');
        }
    }
    #[On('deniedDelete')]
    public function deniedDelete()
    {
        $this->user = '';
    }
    //====================== Render

    public function render()
    {
        $users = User::search($this->search)->paginate(15);

        return view('livewire.user.user-component', ['users' => $users]);
    }
}
