{% extends "base.html" %}
{% from "components/ui.html" import page_header, breadcrumb_nav, button, filter_badge %}

{% block content %}
{% set breadcrumbs = [
    {'text': 'Clients'}
] %}

{{ page_header(
    icon_class='fas fa-users',
    title_text='Clients',
    subtitle_text='Manage your clients here',
    breadcrumbs=breadcrumbs,
    actions_html='<a href="' + url_for("clients.create_client") + '" class="btn btn-primary"><i class="fas fa-plus mr-2"></i>Create Client</a>' if (current_user.is_admin or has_permission('create_clients')) else None
) }}

<div class="bg-card-light dark:bg-card-dark p-6 rounded-lg shadow mb-6">
    <div class="flex justify-between items-center mb-4">
        <h2 class="text-lg font-semibold">{{ _('Filter Clients') }}</h2>
        <button type="button" class="px-3 py-1.5 text-sm bg-background-light dark:bg-background-dark rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors" id="toggleFilters" onclick="toggleFilterVisibility()" title="{{ _('Toggle Filters') }}">
            <i class="fas fa-chevron-up" id="filterToggleIcon"></i>
        </button>
    </div>
    <div id="filterBody">
    <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4" id="clientsFilterForm" data-filter-form>
        <div>
            <label for="clients-filter-search" class="form-label">Search</label>
            <input type="text" name="search" id="clients-filter-search" value="{{ search or '' }}" class="form-input">
        </div>
        <div>
            <label for="status" class="form-label">Status</label>
            <select name="status" id="status" class="form-input">
                <option value="all" {% if status == 'all' %}selected{% endif %}>All</option>
                <option value="active" {% if status == 'active' %}selected{% endif %}>Active</option>
                <option value="inactive" {% if status == 'inactive' %}selected{% endif %}>Inactive</option>
            </select>
        </div>
    </form>
    </div>
</div>

<div class="bg-card-light dark:bg-card-dark p-6 rounded-lg shadow overflow-visible" id="clientsContainer">
    {% include 'clients/_clients_list.html' %}
</div>

{% if current_user.is_admin %}
<form id="clients-bulk-status-form" method="POST" action="{{ url_for('clients.bulk_status_change') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="hidden" name="new_status" id="clientsBulkNewStatus" value="">
</form>
<form id="clients-bulk-delete-form" method="POST" action="{{ url_for('clients.bulk_delete_clients') }}" class="hidden">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
</form>
{% endif %}

{% endblock %}

{% block scripts_extra %}
<style>
.filter-collapsed { display: none !important; }
.filter-toggle-transition { transition: all 0.3s ease-in-out; }
</style>
<script>
function toggleFilterVisibility() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    const toggleButton = document.getElementById('toggleFilters');
    if (!filterBody || !toggleIcon || !toggleButton) return;
    
    const isCollapsed = filterBody.classList.contains('filter-collapsed');
    
    if (isCollapsed) {
        // Show filters
        filterBody.classList.remove('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-down');
        toggleIcon.classList.add('fa-chevron-up');
        toggleButton.title = '{{ _('Hide Filters') }}';
        localStorage.setItem('clientListFiltersVisible', 'true');
    } else {
        // Hide filters
        filterBody.classList.add('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-up');
        toggleIcon.classList.add('fa-chevron-down');
        toggleButton.title = '{{ _('Show Filters') }}';
        localStorage.setItem('clientListFiltersVisible', 'false');
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    const toggleButton = document.getElementById('toggleFilters');
    if (!filterBody || !toggleIcon || !toggleButton) return;
    
    const filtersVisible = localStorage.getItem('clientListFiltersVisible');
    if (filtersVisible === 'false') {
        filterBody.classList.add('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-up');
        toggleIcon.classList.add('fa-chevron-down');
        toggleButton.title = '{{ _('Show Filters') }}';
    } else {
        // Explicitly set the icon to chevron-up when filter is visible
        filterBody.classList.remove('filter-collapsed');
        toggleIcon.classList.remove('fa-chevron-down');
        toggleIcon.classList.add('fa-chevron-up');
        toggleButton.title = '{{ _('Hide Filters') }}';
    }
    setTimeout(() => { filterBody.classList.add('filter-toggle-transition'); }, 100);
});

// Clients Filter Handler - AJAX filtering
(function() {
    'use strict';
    
    let filterTimeout = null;
    let searchTimeout = null;
    
    function getFilterParams() {
        const form = document.getElementById('clientsFilterForm');
        if (!form) return {};
        
        const params = {};
        
        // Get search input value directly
        const searchInput = form.querySelector('input[name="search"]');
        if (searchInput) {
            const searchValue = searchInput.value.trim();
            if (searchValue) {
                params.search = searchValue;
            }
        }
        
        // Get other form fields from FormData
        const formData = new FormData(form);
        for (const [key, value] of formData.entries()) {
            if (key === 'search') continue;
            const trimmed = String(value || '').trim();
            if (trimmed && trimmed !== '' && trimmed !== 'all') {
                params[key] = trimmed;
            }
        }
        
        // Always include status, default to "all" if not set
        if (!params.status) {
            params.status = 'all';
        }
        
        return params;
    }
    
    function buildFilterUrl() {
        const params = getFilterParams();
        const queryString = new URLSearchParams(params).toString();
        return `/clients?${queryString}`;
    }
    
    function applyFilters() {
        const url = buildFilterUrl();
        const container = document.getElementById('clientsListContainer');
        
        if (!container) {
            console.error('clientsListContainer not found');
            return;
        }
        
        // Show loading state
        container.style.opacity = '0.5';
        container.style.pointerEvents = 'none';
        
        // Update URL
        if (window.history && window.history.pushState) {
            window.history.pushState({}, '', url);
        }
        
        // Fetch filtered results
        fetch(url, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'text/html'
            },
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.text();
        })
        .then(html => {
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html.trim();
            
            const newContainer = tempDiv.querySelector('#clientsListContainer');
            
            if (newContainer) {
                container.innerHTML = newContainer.innerHTML;
            } else {
                const match = html.trim().match(/<div[^>]*id=["']clientsListContainer["'][^>]*>([\s\S]*?)<\/div>\s*$/);
                if (match && match[1]) {
                    container.innerHTML = match[1];
                } else {
                    container.innerHTML = html;
                }
            }
        })
        .catch(error => {
            console.error('Filter error:', error);
            container.style.opacity = '';
            container.style.pointerEvents = '';
            if (window.toastManager) {
                window.toastManager.show('Failed to filter clients. Please refresh the page.', 'error');
            } else if (window.showToast) {
                window.showToast('Failed to filter clients. Please refresh the page.', 'error');
            }
        })
        .finally(() => {
            container.style.opacity = '';
            container.style.pointerEvents = '';
        });
    }
    
    function debouncedApplyFilters(delay = 100) {
        if (filterTimeout) {
            clearTimeout(filterTimeout);
        }
        filterTimeout = setTimeout(applyFilters, delay);
    }
    
    function debouncedSearch(delay = 500) {
        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }
        searchTimeout = setTimeout(applyFilters, delay);
    }
    
    // Initialize when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('clientsFilterForm');
        if (!form) {
            console.error('Clients filter form not found');
            return;
        }
        
        // Auto-submit on dropdown changes
        form.querySelectorAll('select').forEach(select => {
            select.addEventListener('change', () => {
                debouncedApplyFilters(100);
            });
        });
        
        // Auto-submit on search input (debounced)
        const searchInput = form.querySelector('input[name="search"]');
        if (searchInput) {
            searchInput.addEventListener('input', () => {
                debouncedSearch(500);
            });
            
            // Submit on Enter
            searchInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    if (searchTimeout) {
                        clearTimeout(searchTimeout);
                    }
                    applyFilters();
                }
            });
        }
        
        // Prevent form submission (use AJAX instead)
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }
            if (filterTimeout) {
                clearTimeout(filterTimeout);
            }
            applyFilters();
        });
    });
})();

{% if current_user.is_admin %}
function toggleAllClients(){
    const selectAll = document.getElementById('selectAll');
    document.querySelectorAll('.client-checkbox').forEach(cb => cb.checked = !!(selectAll && selectAll.checked));
    updateClientsBulkState();
}
function updateClientsBulkState(){
    const selected = document.querySelectorAll('.client-checkbox:checked').length;
    const btn = document.getElementById('bulkActionsBtn');
    const cnt = document.getElementById('selectedCount');
    if (cnt) cnt.textContent = selected;
    if (btn) btn.disabled = selected === 0;
}
function closeAllMenus(){
    document.querySelectorAll('.bulk-menu').forEach(m => m.classList.add('hidden'));
}
function openMenu(triggerEl, menuId){
    const menu = document.getElementById(menuId);
    if (!menu) return;
    const willOpen = menu.classList.contains('hidden');
    closeAllMenus();
    if (!willOpen) return;
    // Position menu (dropup if not enough space below)
    menu.style.top = '';
    menu.style.bottom = '';
    const rect = triggerEl.getBoundingClientRect();
    const menuHeight = menu.offsetHeight || 200;
    const spaceBelow = window.innerHeight - rect.bottom;
    const spaceAbove = rect.top;
    if (spaceBelow < menuHeight + 16 && spaceAbove > menuHeight + 16){
        menu.style.bottom = 'calc(100% + 8px)';
    } else {
        menu.style.top = 'calc(100% + 8px)';
    }
    menu.classList.remove('hidden');
}
// Click outside to close
document.addEventListener('click', function(e){
    const insideTrigger = e.target.closest('#bulkActionsBtn');
    const insideMenu = e.target.closest('#clientsBulkMenu');
    if (!insideTrigger && !insideMenu){ closeAllMenus(); }
});
// Close on Escape
document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeAllMenus(); });

function showBulkDeleteConfirm(){
    const count = document.querySelectorAll('.client-checkbox:checked').length;
    if (count === 0) return false;
    const msg = `Are you sure you want to delete ${count} client(s)? Clients with projects will be skipped.`;
    if (window.showConfirm){ window.showConfirm(msg, { title: 'Delete Clients', confirmText: 'Delete', variant: 'danger' }).then(function(ok){ if (ok) submitClientsBulkDelete(); }); }
    return false;
}
function submitClientsBulkDelete(){
    const form = document.getElementById('clients-bulk-delete-form');
    form.querySelectorAll('input[name="client_ids[]"]').forEach(n => n.remove());
    document.querySelectorAll('.client-checkbox:checked').forEach(cb => {
        const i = document.createElement('input'); i.type='hidden'; i.name='client_ids[]'; i.value=cb.value; form.appendChild(i);
    });
    form.submit();
}
function showBulkStatusChange(newStatus){
    const count = document.querySelectorAll('.client-checkbox:checked').length;
    if (count === 0) return false;
    const label = {active:'Active', inactive:'Inactive'}[newStatus] || newStatus;
    const msg = `Are you sure you want to mark ${count} client(s) as ${label}?`;
    if (window.showConfirm){ window.showConfirm(msg, { title: 'Change Client Status', confirmText: 'Change' }).then(function(ok){ if (ok){ document.getElementById('clientsBulkNewStatus').value=newStatus; submitClientsBulkStatus(); }}); }
    return false;
}
function submitClientsBulkStatus(){
    const form = document.getElementById('clients-bulk-status-form');
    form.querySelectorAll('input[name="client_ids[]"]').forEach(n => n.remove());
    document.querySelectorAll('.client-checkbox:checked').forEach(cb => {
        const i = document.createElement('input'); i.type='hidden'; i.name='client_ids[]'; i.value=cb.value; form.appendChild(i);
    });
    form.submit();
}
{% endif %}
</script>
{% endblock %}
