<?php

namespace App\Livewire\SuperAdmin;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Hash;

class Users extends Component
{
    use WithPagination;

    protected $paginationTheme = 'tailwind';

    public $search = '';
    public $showModal = false;
    public $editMode = false;

    public $userId;
    public $name;
    public $email;
    public $password;
    public $role;
    public $is_active = true;

    protected function rules()
    {
        return [
            'name' => 'required|string|min:3',
            'email' => 'required|email',
            'role' => 'required',
            'password' => $this->editMode
                ? 'nullable|min:8'
                : 'required|min:8',
        ];
    }

    public function render()
    {
        return view('livewire.superadmin.users', [
            'users' => User::with('roles')
                ->where(function ($q) {
                    $q->where('name', 'like', "%{$this->search}%")
                      ->orWhere('email', 'like', "%{$this->search}%");
                })
                ->paginate(10),
            'roles' => Role::all(),
        ]);
    }

    public function toggleStatus(User $user)
    {
        $user->update([
            'is_active' => ! $user->is_active
        ]);
    }

    public function create()
    {
        $this->resetFields();
        $this->editMode = false;
        $this->showModal = true;
    }

    public function edit(User $user)
    {
        $this->userId = $user->id;
        $this->name = $user->name;
        $this->email = $user->email;
        $this->role = $user->roles->first()?->name;
        $this->is_active = $user->is_active;

        $this->password = null; // MUY IMPORTANTE

        $this->editMode = true;
        $this->showModal = true;
    }

    public function save()
    {
        $this->validate();

        if ($this->editMode) {
            $user = User::findOrFail($this->userId);

            $data = [
                'name' => $this->name,
                'email' => $this->email,
                'is_active' => $this->is_active,
            ];

            // SOLO si se escribió una nueva contraseña
            if (!empty($this->password)) {
                $data['password'] = Hash::make($this->password);
            }

            $user->update($data);
        } else {
            $user = User::create([
                'name' => $this->name,
                'email' => $this->email,
                'password' => Hash::make($this->password),
                'is_active' => true,
            ]);
        }

        $user->syncRoles([$this->role]);

        $this->showModal = false;
        $this->resetFields();
    }

    public function suspend(User $user)
    {
        $user->update(['is_active' => false]);
    }

    public function delete(User $user)
    {
        $user->delete();
    }

    private function resetFields()
    {
        $this->reset([
            'userId',
            'name',
            'email',
            'password',
            'role',
            'is_active'
        ]);
    }
}
