<?php

namespace App\Livewire;

use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class UsersPage extends Component
{
    public string $search = '';

    public string $roleFilter = 'all';

    public string $statusFilter = 'all';

    public ?int $selectedUserId = null;

    public string $selectedRole = 'user';

    public function selectUser(int $userId): void
    {
        $this->selectedUserId = $userId;
        $user = User::query()->find($userId);
        if ($user !== null) {
            $this->selectedRole = in_array((string) $user->role, ['super_admin', 'superadmin'], true)
                ? 'super_admin'
                : (string) $user->role;
        }
    }

    public function suspendSelectedUser(): void
    {
        $viewer = auth()->user();
        if ($viewer === null || ! $viewer->isSuperAdmin() || $this->selectedUserId === null) {
            return;
        }

        $target = User::query()->find($this->selectedUserId);
        if ($target === null) {
            return;
        }
        if ((int) $target->id === (int) $viewer->id) {
            session()->flash('toast', (string) __('budgets.users_page.cannot_suspend_self'));

            return;
        }

        $target->suspended_at = now();
        $target->save();
        session()->flash('toast', (string) __('budgets.users_page.user_suspended'));
    }

    public function reactivateSelectedUser(): void
    {
        $viewer = auth()->user();
        if ($viewer === null || ! $viewer->isSuperAdmin() || $this->selectedUserId === null) {
            return;
        }

        $target = User::query()->find($this->selectedUserId);
        if ($target === null) {
            return;
        }

        $target->suspended_at = null;
        $target->save();
        session()->flash('toast', (string) __('budgets.users_page.user_reactivated'));
    }

    public function saveSelectedRole(): void
    {
        $viewer = auth()->user();
        if ($viewer === null || ! $viewer->isSuperAdmin() || $this->selectedUserId === null) {
            return;
        }

        $target = User::query()->find($this->selectedUserId);
        if ($target === null) {
            return;
        }

        if ((int) $target->id === (int) $viewer->id && ! in_array($this->selectedRole, ['super_admin', 'superadmin'], true)) {
            session()->flash('toast', (string) __('budgets.users_page.cannot_demote_self'));

            return;
        }

        $target->role = $this->selectedRole === 'super_admin' ? 'super_admin' : $this->selectedRole;
        $target->save();
        session()->flash('toast', (string) __('budgets.users_page.role_updated'));
    }

    public function render()
    {
        return view('livewire.users-page')
            ->title((string) __('budgets.nav.users'));
    }
}
