<?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\Attributes\Layout;
use Livewire\Component;

#[Layout('components.layouts.app')]
class ManageUsers extends Component
{
    public string $invite_email = '';
    public bool $send_email = false;
    public Collection $users;
    public Collection $invitations;

    public function mount()
    {
        // Load data since route is already protected by middleware
        $this->users = User::all();
        $this->invitations = Invitation::orderBy('accepted_at', 'desc')->get();
    }

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

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

        $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
        $emailSent = $this->send_email;
        if ($emailSent) {
            Mail::to($inv->email)->send(new InvitationMail($inv));
        }

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

        // Refresh the data
        $this->invitations->prepend($inv);
        $this->reset(['invite_email', 'send_email']);

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

    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 deleteInvitation(Invitation $invitation)
    {
        $this->authorize('invite', User::class);

        // Only allow deletion of pending invitations
        if (!$invitation->isPending()) {
            session()->flash('error', 'Cannot delete accepted invitations.');
            return;
        }

        $invitation->delete();

        // Refresh the data
        $this->invitations = Invitation::orderBy('accepted_at', 'desc')->get();

        session()->flash('success', 'Invitation deleted successfully.');
    }

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