<?php

namespace App\Livewire;

use App\Mail\InvitationMail;
use App\Models\Invitation;
use App\Models\User;
use Flux\Flux;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Mail;
use Livewire\Component;

class ManageUsers extends Component
{
    public string $invite_email = '';
    public bool $send_email = false;
    public Collection $users;
    public Collection $invitations;

    public function mount()
    {
        // Only load data if user is authorized to view it
        if (auth()->user()->can('viewAny', User::class)) {
            $this->users = User::all();
            $this->invitations = Invitation::orderBy('accepted_at', 'desc')->get();
        }
    }

    public function inviteUser()
    {
        $this->authorize('invite', User::class);

        $inv = Invitation::create([
            'code' => str()->random(50),
            'email' => $this->invite_email,
            'invited_by' => auth()->user()->id,
            'expires_at' => now()->addDays(7),
        ]);

        // Send email if checkbox is checked
        if ($this->send_email) {
            Mail::to($inv->email)->send(new InvitationMail($inv));
        }

        Flux::modal('invite-user')->close();

        // Refresh the data
        $this->invitations = Invitation::all();
        $this->invite_email = '';
        $this->send_email = false;

        session()->flash('success', 'Invitation created successfully' . ($emailSent ? ' and email sent' : '') . '.');
    }

    public function deleteUser(User $user)
    {
        $this->authorize('delete', $user);

        $user->delete();

        // Refresh the data
        $this->users = User::all();
    }

    public function changeUserRole(User $user, string $role)
    {
        $this->authorize('update', $user);

        // Prevent admins from demoting themselves
        if ($user->id === auth()->id() && $role === 'user') {
            session()->flash('error', 'You cannot demote yourself from admin.');
            return;
        }

        $isAdmin = $role === 'admin';
        $user->update(['is_admin' => $isAdmin]);

        // Refresh the data
        $this->users = User::all();

        session()->flash('success', "User role updated to {$role}.");
    }

    public function render()
    {
        return view('livewire.manage-users');
    }
}
