{% extends 'base.html' %}

{% block title %}Edit Admin - {{ admin.get_full_name }} - HAVEN GRAZURI ADVANCE{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
    <div class="px-4 py-6 sm:px-0">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex justify-between items-center">
                <div>
                    <h2 class="text-2xl font-bold text-gray-900">Edit Admin: {{ admin.get_full_name }}</h2>
                    <p class="mt-1 text-sm text-gray-600">Update admin user information and permissions.</p>
                </div>
                <div>
                    <a href="{% url 'users:admin_list' %}" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                        <span>←</span>
                        Back to Admin List
                    </a>
                </div>
            </div>
        </div>

        <!-- Admin Form -->
        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                <form method="post" class="space-y-6">
                    {% csrf_token %}

                    <!-- Basic Information -->
                    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                        <div>
                            <label for="first_name" class="block text-sm font-medium text-gray-700">First Name</label>
                            <input type="text" name="first_name" id="first_name" value="{{ admin.first_name }}" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            <p class="mt-1 hidden text-sm text-red-600" id="first_name_error">Please enter a first name.</p>
                        </div>
                        <div>
                            <label for="last_name" class="block text-sm font-medium text-gray-700">Last Name</label>
                            <input type="text" name="last_name" id="last_name" value="{{ admin.last_name }}" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            <p class="mt-1 hidden text-sm text-red-600" id="last_name_error">Please enter a last name.</p>
                        </div>
                    </div>

                    <!-- Contact Information -->
                    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                        <div>
                            <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
                            <input type="email" name="email" id="email" value="{{ admin.email }}" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                            <p class="mt-1 hidden text-sm text-red-600" id="email_error">Please enter a valid email address.</p>
                        </div>
                        
                        <div>
                            <label for="branch" class="block text-sm font-medium text-gray-700">Branch</label>
                            <select name="branch" id="branch" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                <option value="">Select branch (optional)</option>
                                {% for branch in branches %}
                                <option value="{{ branch.id }}" {% if admin.branch_id == branch.id %}selected{% endif %}>{{ branch.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div>
                            <label for="phone_number" class="block text-sm font-medium text-gray-700">Phone Number</label>
                            <input type="tel" name="phone_number" id="phone_number" value="{{ admin.phone_number }}" required
                                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm"
                                   placeholder="+254XXXXXXXXX">
                            <p class="mt-1 hidden text-sm text-red-600" id="phone_error">Please enter a valid phone number (+254XXXXXXXXX).</p>
                        </div>
                    </div>

                    <!-- Status and Permissions -->
                    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
                        <div>
                            <label for="status" class="block text-sm font-medium text-gray-700">Status</label>
                            <select name="status" id="status" required
                                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                {% for status_value, status_label in status_choices %}
                                <option value="{{ status_value }}" {% if admin.status == status_value %}selected{% endif %}>
                                    {{ status_label }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>
                        <div>
                            <label for="role" class="block text-sm font-medium text-gray-700">Role</label>
                            <select name="role" id="role" required
                                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                {% for role_value, role_label in role_choices %}
                                <option value="{{ role_value }}" {% if admin.role == role_value %}selected{% endif %}>
                                    {{ role_label }}
                                </option>
                                {% endfor %}
                            </select>
                            <p class="mt-1 text-xs text-gray-500">
                                <strong>Admin:</strong> Full system access<br>
                                <strong>Team Leader:</strong> Manage team and portfolio<br>
                                <strong>Loan Officer:</strong> Manage assigned borrowers<br>
                                <strong>Secretary:</strong> Administrative support<br>
                                <strong>Auditor:</strong> Review and audit access
                            </p>
                        </div>
                    </div>

                    <!-- Password Change -->
                    <div class="border-t border-gray-200 pt-6">
                        <h3 class="text-lg font-medium text-gray-900">Change Password</h3>
                        <p class="mt-1 text-sm text-gray-600">Leave blank to keep current password.</p>
                        <div class="mt-4 grid grid-cols-1 gap-6 sm:grid-cols-2">
                            <div>
                                <label for="new_password" class="block text-sm font-medium text-gray-700">New Password</label>
                                <input type="password" name="new_password" id="new_password"
                                       class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                <p class="mt-1 hidden text-sm text-red-600" id="new_password_error">Password must be at least 8 characters long.</p>
                            </div>
                            <div>
                                <label for="confirm_password" class="block text-sm font-medium text-gray-700">Confirm Password</label>
                                <input type="password" name="confirm_password" id="confirm_password"
                                       class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring-primary sm:text-sm">
                                <p class="mt-1 hidden text-sm text-red-600" id="confirm_password_error">Passwords do not match.</p>
                            </div>
                        </div>
                    </div>

                    <!-- Submit Buttons -->
                    <div class="flex justify-end space-x-3">
                        <a href="{% url 'users:admin_list' %}"
                           class="inline-flex justify-center py-2 px-4 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            Cancel
                        </a>
                        <button type="submit"
                                class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                            Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    const form = document.querySelector('form');
    const inputs = {
        firstName: document.getElementById('first_name'),
        lastName: document.getElementById('last_name'),
        email: document.getElementById('email'),
        phone: document.getElementById('phone_number'),
        newPassword: document.getElementById('new_password'),
        confirmPassword: document.getElementById('confirm_password')
    };
    
    // Show error message
    function showError(inputId, show = true) {
        const error = document.getElementById(`${inputId}_error`);
        const input = document.getElementById(inputId);
        if (error && input) {
            error.classList.toggle('hidden', !show);
            input.classList.toggle('border-red-500', show);
        }
    }
    
    // Hide error message
    function hideError(inputId) {
        showError(inputId, false);
    }
    
    // Validate email format
    function isValidEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }
    
    // Validate phone number format
    function isValidPhone(phone) {
        return /^\+254\d{9}$/.test(phone);
    }
    
    // Real-time validation
    inputs.email.addEventListener('input', function() {
        if (this.value && !isValidEmail(this.value)) {
            showError('email');
        } else {
            hideError('email');
        }
    });
    
    inputs.phone.addEventListener('input', function() {
        if (this.value && !isValidPhone(this.value)) {
            showError('phone');
        } else {
            hideError('phone');
        }
    });
    
    inputs.confirmPassword.addEventListener('input', function() {
        if (inputs.newPassword.value && this.value !== inputs.newPassword.value) {
            showError('confirm_password');
        } else {
            hideError('confirm_password');
        }
    });
    
    inputs.newPassword.addEventListener('input', function() {
        if (this.value && this.value.length < 8) {
            showError('new_password');
        } else {
            hideError('new_password');
        }
        
        if (inputs.confirmPassword.value) {
            if (this.value !== inputs.confirmPassword.value) {
                showError('confirm_password');
            } else {
                hideError('confirm_password');
            }
        }
    });
    
    // Form submission validation
    form.addEventListener('submit', function(e) {
        let isValid = true;
        
        // Reset all error messages
        Object.keys(inputs).forEach(key => {
            const inputId = inputs[key].id;
            hideError(inputId);
        });
        
        // Required fields validation
        if (!inputs.firstName.value.trim()) {
            showError('first_name');
            isValid = false;
        }
        
        if (!inputs.lastName.value.trim()) {
            showError('last_name');
            isValid = false;
        }
        
        if (!inputs.email.value.trim() || !isValidEmail(inputs.email.value)) {
            showError('email');
            isValid = false;
        }
        
        if (!inputs.phone.value.trim() || !isValidPhone(inputs.phone.value)) {
            showError('phone');
            isValid = false;
        }
        
        // Password validation (only if either password field is filled)
        if (inputs.newPassword.value || inputs.confirmPassword.value) {
            if (inputs.newPassword.value.length < 8) {
                showError('new_password');
                isValid = false;
            }
            
            if (inputs.newPassword.value !== inputs.confirmPassword.value) {
                showError('confirm_password');
                isValid = false;
            }
        }
        
        if (!isValid) {
            e.preventDefault();
        }
    });
</script>
{% endblock %}