<x-admin-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Edit User') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <form method="POST" action="/admin/users/{{ $user->id }}" id="userUpdateForm">
                        @csrf
                        @method('PUT')
                        
                        <!-- Debug Route Check -->
                        @php
                            try {
                                $updateRoute = route('admin.users.update', $user->id);
                                $showRoute = route('admin.users.show', $user->id);
                                $routeError = null;
                            } catch (Exception $e) {
                                $routeError = $e->getMessage();
                                $updateRoute = 'ERROR: ' . $e->getMessage();
                                $showRoute = 'ERROR: ' . $e->getMessage();
                            }
                        @endphp

                        <!-- Name -->
                        <div class="mb-4">
                            <label for="name" class="block text-sm font-medium text-gray-700">Name</label>
                            <input type="text" name="name" id="name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" value="{{ old('name', $user->name) }}" required>
                            @error('name')
                                <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Email -->
                        <div class="mb-4">
                            <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
                            <input type="email" name="email" id="email" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" value="{{ old('email', $user->email) }}" required>
                            @error('email')
                                <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Password (Optional) -->
                        <div class="mb-4">
                            <label for="password" class="block text-sm font-medium text-gray-700">Password (Leave blank to keep current)</label>
                            <input type="password" name="password" id="password" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                            @error('password')
                                <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Role -->
                        <div class="mb-4">
                            <label for="role" class="block text-sm font-medium text-gray-700">Role</label>
                            <select name="role" id="role" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                @foreach($roles as $role)
                                    <option value="{{ $role->name }}" {{ $user->hasRole($role->name) ? 'selected' : '' }}>{{ $role->name }}</option>
                                @endforeach
                            </select>
                            @error('role')
                                <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Tenant -->
                        <div class="mb-4">
                            <label for="tenant_id" class="block text-sm font-medium text-gray-700">Tenant</label>
                            <select name="tenant_id" id="tenant_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                <option value="">-- None (Platform Admin) --</option>
                                @foreach($tenants as $tenant)
                                    <option value="{{ $tenant->id }}" {{ $user->tenant_id == $tenant->id ? 'selected' : '' }}>{{ $tenant->name }} ({{ $tenant->domain }})</option>
                                @endforeach
                            </select>
                            @error('tenant_id')
                                <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- Status -->
                        <div class="mb-4">
                            <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                            <select name="status" id="status" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" onchange="console.log('Status changed to:', this.value)">
                                <option value="active" {{ $user->status === 'active' ? 'selected' : '' }}>Active</option>
                                <option value="inactive" {{ $user->status === 'inactive' ? 'selected' : '' }}>Inactive</option>
                            </select>
                            @error('status')
                                <p class="text-red-500 text-xs mt-1">{{ $message }}</p>
                            @enderror
                            <!-- Status Debug -->
                            <p class="text-xs text-gray-500 mt-1">Current status: {{ $user->status }}</p>
                            <input type="hidden" name="status_debug" value="{{ $user->status }}">
                        </div>

                        <!-- Security Section -->
                        <div class="mt-8 border-t pt-6">
                            <h3 class="text-lg font-medium text-gray-900 mb-4">Security Actions</h3>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div class="p-4 bg-gray-50 rounded-md border">
                                    <h4 class="font-medium text-gray-700">Login Activity</h4>
                                    <p class="text-sm text-gray-500 mb-3">View all login attempts for this user.</p>
                                    <a href="{{ route('admin.login-logs.index', ['email' => $user->email]) }}" class="text-indigo-600 hover:text-indigo-800 text-sm font-medium">View Login Logs &rarr;</a>
                                </div>
                                
                                <div class="p-4 bg-gray-50 rounded-md border">
                                    <h4 class="font-medium text-gray-700">IP Blocking</h4>
                                    @if($lastIp)
                                        <p class="text-sm text-gray-500 mb-3">Last known IP: <span class="font-mono bg-gray-200 px-1 rounded">{{ $lastIp }}</span></p>
                                        <form action="{{ route('admin.blocked-ips.store') }}" method="POST" onsubmit="return confirm('Are you sure you want to block this IP?');">
                                            @csrf
                                            <input type="hidden" name="ip_address" value="{{ $lastIp }}">
                                            <input type="hidden" name="reason" value="Blocked from User Edit page for user: {{ $user->email }}">
                                            <button type="submit" class="text-red-600 hover:text-red-800 text-sm font-medium">Block Last IP &rarr;</button>
                                        </form>
                                    @else
                                        <p class="text-sm text-gray-500">No login history found to block IP.</p>
                                    @endif
                                </div>
                            </div>
                        </div>

                        <div class="flex items-center justify-end mt-4">
                            <a href="{{ route('admin.users.index') }}" class="text-gray-600 hover:text-gray-900 mr-4">Cancel</a>
                            <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded">
                                Update User
                            </button>
                        </div>
                        
                        <!-- Debug Information -->
                        <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded text-sm">
                            <p><strong>Debug Info:</strong></p>
                            <p>Form Action: /admin/users/{{ $user->id }}</p>
                            <p>Update Route: {{ $updateRoute ?? 'N/A' }}</p>
                            <p>Show Route: {{ $showRoute ?? 'N/A' }}</p>
                            <p>Route Error: {{ $routeError ?? 'None' }}</p>
                            <p>Method: PUT</p>
                            <p>User ID: {{ $user->id }}</p>
                            <p>CSRF Token: {{ csrf_token() }}</p>
                            <p>Current URL: {{ url()->current() }}</p>
                        </div>
                        
                        <!-- Test Form -->
                        <div class="mt-4 p-3 bg-blue-50 border border-blue-200 rounded text-sm">
                            <p><strong>Test Update:</strong></p>
                            <div style="margin-top: 10px;">
                                <button type="button" onclick="console.log('Test button clicked - form should submit')" class="bg-blue-600 hover:bg-blue-700 text-white text-sm py-1 px-3 rounded">
                                    Test Form Submission
                                </button>
                                <button type="button" onclick="document.getElementById('status').value = document.getElementById('status').value === 'active' ? 'inactive' : 'active'; console.log('Status toggled to:', document.getElementById('status').value);" class="bg-green-600 hover:bg-green-700 text-white text-sm py-1 px-3 rounded ml-2">
                                    Toggle Status Field
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('userUpdateForm');
            const submitBtn = form.querySelector('button[type="submit"]');
            
            form.addEventListener('submit', function(e) {
                console.log('Form submission started');
                console.log('Form action:', form.action);
                console.log('Form method:', form.method);
                console.log('FormData:', new FormData(form));
                
                // Disable button to prevent double submission
                submitBtn.disabled = true;
                submitBtn.textContent = 'Updating...';
                
                // Re-enable after 5 seconds if form doesn't submit
                setTimeout(function() {
                    submitBtn.disabled = false;
                    submitBtn.textContent = 'Update User';
                    console.log('Form submission timeout - button re-enabled');
                }, 5000);
            });
        });
    </script>
                </div>
            </div>
        </div>
    </div>
</x-admin-layout>
