<?php

namespace App\Livewire\Users;

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

class UserManager extends Component
{
    use WithPagination;

    // Filtros
    public string $search = '';
    public string $filterRole = '';

    // Modal
    public bool $showModal = false;
    public bool $showDeleteModal = false;
    public bool $editing = false;
    public ?int $userId = null;

    // Campos formulario
    public string $name = '';
    public string $email = '';
    public string $password = '';
    public string $password_confirmation = '';
    public string $selectedRole = '';
    public bool $is_active = true;

    // Delete
    public ?int $deleteUserId = null;
    public string $deleteUserName = '';

    protected $queryString = [
        'search' => ['except' => ''],
        'filterRole' => ['except' => ''],
    ];

    public function updatingSearch(): void
    {
        $this->resetPage();
    }

    public function updatingFilterRole(): void
    {
        $this->resetPage();
    }

    public function openCreate(): void
    {
        $this->resetForm();
        $this->editing = false;
        $this->showModal = true;
    }

    public function openEdit(int $id): void
    {
        $user = User::findOrFail($id);
        $this->userId = $user->id;
        $this->name = $user->name;
        $this->email = $user->email;
        $this->selectedRole = $user->getRoleNames()->first() ?? '';
        $this->is_active = $user->is_active;
        $this->password = '';
        $this->password_confirmation = '';
        $this->editing = true;
        $this->showModal = true;
    }

    public function save(): void
    {
        $rules = [
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email' . ($this->editing ? ',' . $this->userId : ''),
            'selectedRole' => 'required|string|exists:roles,name',
            'is_active' => 'boolean',
        ];

        if (!$this->editing) {
            $rules['password'] = ['required', 'confirmed', Password::min(8)];
        } else {
            $rules['password'] = ['nullable', 'confirmed', Password::min(8)];
        }

        $validated = $this->validate($rules);

        if ($this->editing) {
            $user = User::findOrFail($this->userId);
            $user->name = $this->name;
            $user->email = $this->email;
            $user->is_active = $this->is_active;
            if (!empty($this->password)) {
                $user->password = Hash::make($this->password);
            }
            $user->save();
            $user->syncRoles([$this->selectedRole]);

            session()->flash('message', 'Usuario actualizado correctamente.');
        } else {
            $user = User::create([
                'name' => $this->name,
                'email' => $this->email,
                'password' => Hash::make($this->password),
                'is_active' => $this->is_active,
            ]);
            $user->assignRole($this->selectedRole);

            session()->flash('message', 'Usuario creado correctamente.');
        }

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

    public function toggleActive(int $id): void
    {
        $user = User::findOrFail($id);
        if ($user->id === auth()->id()) {
            session()->flash('error', 'No puedes desactivar tu propia cuenta.');
            return;
        }
        $user->is_active = !$user->is_active;
        $user->save();

        session()->flash('message', 'Estado del usuario actualizado.');
    }

    public function confirmDelete(int $id): void
    {
        $user = User::findOrFail($id);
        if ($user->id === auth()->id()) {
            session()->flash('error', 'No puedes eliminar tu propia cuenta.');
            return;
        }
        $this->deleteUserId = $id;
        $this->deleteUserName = $user->name;
        $this->showDeleteModal = true;
    }

    public function deleteUser(): void
    {
        $user = User::findOrFail($this->deleteUserId);
        $user->delete();
        $this->showDeleteModal = false;
        $this->deleteUserId = null;
        $this->deleteUserName = '';
        session()->flash('message', 'Usuario eliminado correctamente.');
    }

    public function cancelDelete(): void
    {
        $this->showDeleteModal = false;
        $this->deleteUserId = null;
        $this->deleteUserName = '';
    }

    public function closeModal(): void
    {
        $this->showModal = false;
        $this->resetForm();
    }

    private function resetForm(): void
    {
        $this->userId = null;
        $this->name = '';
        $this->email = '';
        $this->password = '';
        $this->password_confirmation = '';
        $this->selectedRole = '';
        $this->is_active = true;
        $this->resetValidation();
    }

    public function render()
    {
        $query = User::with('roles');

        if ($this->search) {
            $query->where(function ($q) {
                $q->where('name', 'like', '%' . $this->search . '%')
                  ->orWhere('email', 'like', '%' . $this->search . '%');
            });
        }

        if ($this->filterRole) {
            $query->whereHas('roles', fn($q) => $q->where('name', $this->filterRole));
        }

        return view('livewire.users.user-manager', [
            'users' => $query->orderBy('name')->paginate(10),
            'roles' => Role::orderBy('name')->pluck('name'),
        ]);
    }
}
