<?php

namespace App\Livewire\Admin;

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

class UserManagement extends Component
{
    use WithPagination;

    // Properties for form data
    public $name = '';
    public $email = '';
    public $password = '';
    public $password_confirmation = '';
    public $role = '';
    public $phone = '';
    public $address = '';
    public $date_of_birth = '';
    public $is_active = true;

    // Properties for component state
    public $search = '';
    public $statusFilter = '';
    public $sortField = 'created_at';
    public $sortDirection = 'desc';

    protected $rules = [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|min:8|confirmed',
        'role' => 'required|string',
        'phone' => 'nullable|string|max:20',
        'address' => 'nullable|string|max:500',
        'date_of_birth' => 'nullable|date',
        'is_active' => 'boolean',
    ];

    protected $messages = [
        'name.required' => 'Name is required.',
        'email.required' => 'Email is required.',
        'email.email' => 'Please enter a valid email address.',
        'email.unique' => 'This email is already taken.',
        'password.required' => 'Password is required.',
        'password.min' => 'Password must be at least 8 characters.',
        'password.confirmed' => 'Password confirmation does not match.',
        'role.required' => 'Role is required.',
    ];

    public function mount()
    {
        //
    }

    public function openModal($userId = null)
    {
        if ($userId) {
            return redirect()->route('admin.users.edit', $userId);
        } else {
            return redirect()->route('admin.users.create');
        }
    }

    public function delete($userId)
    {
        // Check permission
        if (!auth()->user()->can('users.delete')) {
            FlashMessageService::insufficientPermissions();
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'error', 'You do not have permission to delete users.', 'Insufficient Permissions', 8000);
            
            return;
        }

        try {
            $user = User::findOrFail($userId);
            
            // Prevent admin from deleting themselves
            if ($user->id === auth()->id()) {
                FlashMessageService::cannotDeleteSelf();
                
                // Dispatch flash message event
                $this->dispatch('flashMessage', 'error', 'You cannot delete your own account!', 'Warning', 8000);
                
                return;
            }
            
            $user->delete();
            FlashMessageService::userDeleted();
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'success', 'User deleted successfully!', 'Success', 5000);
            
        } catch (\Exception $e) {
            FlashMessageService::userDeleteFailed();
            
            // Dispatch flash message event
            $this->dispatch('flashMessage', 'error', 'Failed to delete user. Please try again.', 'Error', 8000);
            
            \Log::error('User deletion error: ' . $e->getMessage());
        }
    }

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        
        $this->sortField = $field;
    }

    public function clearFilters()
    {
        $this->search = '';
        $this->statusFilter = '';
        $this->resetPage();
    }

    public function render()
    {
        $query = User::query()
            ->with('roles')
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('name', 'like', '%' . $this->search . '%')
                      ->orWhere('email', 'like', '%' . $this->search . '%')
                      ->orWhere('phone', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->statusFilter !== '', function ($query) {
                $query->where('is_active', $this->statusFilter);
            })
            ->orderBy($this->sortField, $this->sortDirection);

        $users = $query->paginate(10);

        return view('livewire.admin.user-management', [
            'users' => $users
        ]);
    }
}