/**
 * Filtering & Sorting Module
 * Handles: Schema filtering, sorting, pagination
 */
(function($) {
    'use strict';

    window.SchemafyFilters = {
        /**
         * Apply all bulk filters
         */
        applyBulkFilters: function() {
            if (!window.SchemafyBulk || !window.SchemafyBulk.allBulkSchemas) return;

            const searchQuery = $('#schemafy-bulk-search').val().toLowerCase();
            const filterType = $('#schemafy-bulk-filter-type').val();
            const filterStatus = $('#schemafy-bulk-filter-status').val();
            const filterDate = $('#schemafy-bulk-filter-date').val();

            let filteredSchemas = [...window.SchemafyBulk.allBulkSchemas];

            // Search filter
            if (searchQuery) {
                filteredSchemas = filteredSchemas.filter(schema => {
                    const url = (schema.url || '').toLowerCase();
                    const name = (schema.schema_name || '').toLowerCase();
                    const schemaData = (schema.schema_data || '').toLowerCase();
                    return url.includes(searchQuery) || name.includes(searchQuery) || schemaData.includes(searchQuery);
                });
            }

            // Type filter
            if (filterType) {
                const filterTypeLower = filterType.toLowerCase().trim();
                filteredSchemas = filteredSchemas.filter(schema => {
                    if (schema.schema_type) {
                        return schema.schema_type.toLowerCase().trim() === filterTypeLower;
                    }
                    try {
                        const data = JSON.parse(schema.schema_data);
                        const jsonType = data['@type'] || '';
                        return jsonType.toLowerCase().trim() === filterTypeLower;
                    } catch (e) {
                        return false;
                    }
                });
            }

            // Status filter
            if (filterStatus !== '') {
                filteredSchemas = filteredSchemas.filter(schema => {
                    return String(schema.is_active) === filterStatus;
                });
            }

            // Date filter
            if (filterDate) {
                const now = new Date();
                filteredSchemas = filteredSchemas.filter(schema => {
                    if (!schema.created_at) return true;

                    const createdDate = new Date(schema.created_at);
                    const diffTime = now - createdDate;
                    const diffDays = diffTime / (1000 * 60 * 60 * 24);

                    switch (filterDate) {
                        case 'today': return diffDays < 1;
                        case 'yesterday': return diffDays >= 1 && diffDays < 2;
                        case 'week': return diffDays <= 7;
                        case 'month': return diffDays <= 30;
                        case '3months': return diffDays <= 90;
                        case 'year': return diffDays <= 365;
                        default: return true;
                    }
                });
            }

            // Apply sort
            const sortBy = $('#schemafy-bulk-sort').val() || 'date_desc';
            filteredSchemas = this.sortSchemasArray(filteredSchemas, sortBy);

            // Update UI
            this.updateActiveFiltersDisplay();
            this.renderFilteredSchemas(filteredSchemas);
        },

        /**
         * Sort schemas array
         */
        sortSchemasArray: function(schemas, sortBy) {
            const sorted = [...schemas];

            switch (sortBy) {
                case 'date_desc':
                    return sorted.sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0));
                case 'date_asc':
                    return sorted.sort((a, b) => new Date(a.created_at || 0) - new Date(b.created_at || 0));
                case 'name_asc':
                    return sorted.sort((a, b) => (a.schema_name || '').localeCompare(b.schema_name || ''));
                case 'name_desc':
                    return sorted.sort((a, b) => (b.schema_name || '').localeCompare(a.schema_name || ''));
                case 'type_asc':
                    return sorted.sort((a, b) => {
                        const typeA = this.getSchemaType(a);
                        const typeB = this.getSchemaType(b);
                        return typeA.localeCompare(typeB);
                    });
                case 'url_asc':
                    return sorted.sort((a, b) => (a.url || '').localeCompare(b.url || ''));
                default:
                    return sorted;
            }
        },

        /**
         * Get schema type from schema object
         */
        getSchemaType: function(schema) {
            try {
                const data = JSON.parse(schema.schema_data);
                return data['@type'] || '';
            } catch (e) {
                return '';
            }
        },

        /**
         * Sort bulk schemas (wrapper)
         */
        sortBulkSchemas: function() {
            this.applyBulkFilters();
        },

        /**
         * Change items per page
         */
        changeBulkPerPage: function(perPage) {
            if (window.SchemafyBulk) {
                window.SchemafyBulk.bulkPerPage = perPage === 'all' ? 9999 : parseInt(perPage);
                window.SchemafyBulk.currentBulkPage = 1;
            }
            this.applyBulkFilters();
        },

        /**
         * Clear all filters
         */
        clearBulkFilters: function() {
            $('#schemafy-bulk-search').val('');
            $('#schemafy-bulk-filter-type').val('');
            $('#schemafy-bulk-filter-status').val('');
            $('#schemafy-bulk-filter-date').val('');
            $('#schemafy-bulk-sort').val('date_desc');
            $('#schemafy-bulk-per-page').val('25');

            if (window.SchemafyBulk) {
                window.SchemafyBulk.bulkPerPage = 25;
                window.SchemafyBulk.currentBulkPage = 1;
            }

            this.applyBulkFilters();
        },

        /**
         * Update active filters display
         */
        updateActiveFiltersDisplay: function() {
            const $container = $('#schemafy-active-filters');
            const $tagsContainer = $('#schemafy-active-filters-tags');
            const filters = [];

            const searchQuery = $('#schemafy-bulk-search').val();
            const filterType = $('#schemafy-bulk-filter-type').val();
            const filterStatus = $('#schemafy-bulk-filter-status').val();
            const filterDate = $('#schemafy-bulk-filter-date').val();

            if (searchQuery) {
                filters.push({ label: 'Search', value: searchQuery, field: 'search' });
            }
            if (filterType) {
                filters.push({ label: 'Type', value: $('#schemafy-bulk-filter-type option:selected').text(), field: 'type' });
            }
            if (filterStatus !== '') {
                filters.push({ label: 'Status', value: $('#schemafy-bulk-filter-status option:selected').text(), field: 'status' });
            }
            if (filterDate) {
                filters.push({ label: 'Date', value: $('#schemafy-bulk-filter-date option:selected').text(), field: 'date' });
            }

            if (filters.length > 0) {
                $tagsContainer.empty();
                filters.forEach(filter => {
                    const $tag = $(`
                        <span class="schemafy-filter-tag" style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: var(--schemafy-primary); color: white; border-radius: 12px; font-size: 12px; font-weight: 500;">
                            <span>${filter.label}: ${filter.value}</span>
                            <button class="schemafy-remove-filter" data-field="${filter.field}" style="background: none; border: none; color: white; cursor: pointer; font-size: 14px; line-height: 1; padding: 0;">×</button>
                        </span>
                    `);
                    $tagsContainer.append($tag);
                });
                $container.show();

                // Bind remove filter events
                const self = this;
                $('.schemafy-remove-filter').off('click').on('click', function(e) {
                    const field = $(e.target).data('field');
                    switch (field) {
                        case 'search': $('#schemafy-bulk-search').val(''); break;
                        case 'type': $('#schemafy-bulk-filter-type').val(''); break;
                        case 'status': $('#schemafy-bulk-filter-status').val(''); break;
                        case 'date': $('#schemafy-bulk-filter-date').val(''); break;
                    }
                    self.applyBulkFilters();
                });
            } else {
                $container.hide();
            }
        },

        /**
         * Render filtered schemas with pagination
         */
        renderFilteredSchemas: function(schemas) {
            if (!window.SchemafyBulk) return;

            const totalResults = schemas.length;
            const startIndex = (window.SchemafyBulk.currentBulkPage - 1) * window.SchemafyBulk.bulkPerPage;
            const endIndex = startIndex + window.SchemafyBulk.bulkPerPage;
            const paginatedSchemas = schemas.slice(startIndex, endIndex);

            // Update results summary
            $('#schemafy-results-count').text(`${totalResults} schema${totalResults !== 1 ? 's' : ''} found`);
            if (totalResults > 0) {
                $('#schemafy-results-range').text(`Showing ${startIndex + 1}-${Math.min(endIndex, totalResults)} of ${totalResults}`);
            } else {
                $('#schemafy-results-range').text('');
            }

            // Calculate pagination
            const totalPages = Math.ceil(totalResults / window.SchemafyBulk.bulkPerPage);
            const pagination = {
                current_page: window.SchemafyBulk.currentBulkPage,
                total_pages: totalPages,
                total: totalResults,
                per_page: window.SchemafyBulk.bulkPerPage
            };

            // Render table
            window.SchemafyBulk.renderBulkTable(paginatedSchemas, pagination);

            // Bind pagination events
            this.bindPaginationEvents();
        },

        /**
         * Bind pagination click events
         */
        bindPaginationEvents: function() {
            const $container = $('#schemafy-bulk-table-container');
            const self = this;

            $container.off('click', '.schemafy-pagination-btn').on('click', '.schemafy-pagination-btn', function(e) {
                const page = parseInt($(e.currentTarget).data('page'));
                if (window.SchemafyBulk) {
                    window.SchemafyBulk.currentBulkPage = page;
                }
                self.applyBulkFilters();
                $container[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
            });
        },

        /**
         * Populate type filter dropdown from loaded schemas
         */
        populateTypeFilter: function(schemas) {
            const $select = $('#schemafy-bulk-filter-type');
            if (!$select.length || !schemas) return;

            const currentValue = $select.val();

            // Extract unique types from schema data
            const types = new Set();
            schemas.forEach(schema => {
                // Try schema_type field first
                if (schema.schema_type && schema.schema_type.trim()) {
                    types.add(schema.schema_type.trim());
                    return;
                }
                // Fallback to parsing JSON @type
                try {
                    const data = JSON.parse(schema.schema_data);
                    if (data['@type'] && data['@type'].trim()) {
                        types.add(data['@type'].trim());
                    }
                } catch (e) {}
            });

            // Sort types alphabetically
            const sortedTypes = Array.from(types).sort((a, b) => a.localeCompare(b));

            // Rebuild options preserving current selection
            $select.find('option:not(:first)').remove();
            sortedTypes.forEach(type => {
                $select.append($('<option>', { value: type, text: type }));
            });

            // Restore previous selection if still valid
            if (currentValue && sortedTypes.includes(currentValue)) {
                $select.val(currentValue);
            }
        },

        /**
         * Initialize filter event bindings
         */
        initFilterEvents: function() {
            const self = this;
            let searchTimeout = null;

            $(document).on('input', '#schemafy-bulk-search', () => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => self.applyBulkFilters(), 300);
            });

            $(document).on('change', '#schemafy-bulk-filter-type', () => self.applyBulkFilters());
            $(document).on('change', '#schemafy-bulk-filter-status', () => self.applyBulkFilters());
            $(document).on('change', '#schemafy-bulk-filter-date', () => self.applyBulkFilters());
            $(document).on('change', '#schemafy-bulk-sort', () => self.sortBulkSchemas());
            $(document).on('change', '#schemafy-bulk-per-page', (e) => self.changeBulkPerPage(e.target.value));
            $(document).on('click', '#schemafy-bulk-clear-filters', () => self.clearBulkFilters());
        }
    };

})(jQuery);
