import './bootstrap';
import Alpine from 'alpinejs';
import persist from '@alpinejs/persist'



window.Alpine = Alpine;

document.addEventListener('DOMContentLoaded', function () {
    // Theme toggle functionality
    const themeToggle = document.getElementById('theme-toggle');
    const mobileThemeToggle = document.getElementById('theme-toggle-mobile');

    function updateThemeIcons(isDark) {
        // Desktop icons
        const darkIcon = document.getElementById('theme-toggle-dark-icon');
        const lightIcon = document.getElementById('theme-toggle-light-icon');
        if (darkIcon) darkIcon.classList.toggle('hidden', !isDark);
        if (lightIcon) lightIcon.classList.toggle('hidden', isDark);

        // Mobile icons
        const mobileDarkIcon = document.getElementById('theme-toggle-dark-icon-mobile');
        const mobileLightIcon = document.getElementById('theme-toggle-light-icon-mobile');
        const themeText = document.getElementById('theme-toggle-text');

        if (mobileDarkIcon) mobileDarkIcon.classList.toggle('hidden', !isDark);
        if (mobileLightIcon) mobileLightIcon.classList.toggle('hidden', isDark);
        if (themeText) themeText.textContent = isDark ? 'Light Mode' : 'Dark Mode';
    }

    function toggleTheme() {
        const isDark = document.documentElement.classList.toggle('dark');
        localStorage.setItem('theme', isDark ? 'dark' : 'light');
        updateThemeIcons(isDark);
    }

    if (themeToggle) themeToggle.addEventListener('click', toggleTheme);
    if (mobileThemeToggle) mobileThemeToggle.addEventListener('click', toggleTheme);

    // Initialize icons
    updateThemeIcons(document.documentElement.classList.contains('dark'));

    // Mobile menu toggle
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    if (mobileMenuButton) {
        mobileMenuButton.addEventListener('click', function () {
            const menu = document.getElementById('mobile-menu');
            if (menu) menu.classList.toggle('hidden');

            const openIcon = document.getElementById('mobile-menu-open-icon');
            const closeIcon = document.getElementById('mobile-menu-close-icon');
            if (openIcon && closeIcon) {
                openIcon.classList.toggle('hidden');
                closeIcon.classList.toggle('hidden');
            }
        });
    }
});

if (typeof window.initializedInstances === 'undefined') {
    window.initializedInstances = [];
}

// Define the dataTable Alpine component
document.addEventListener('alpine:init', () => {
    Alpine.data('dataTable', ({
        instanceKey,
        dataUrl,
        baseUrl,
        exportUrl,
        bulkUrl,
        columns,
        enableExport,
        enableBulkDelete,
        enableEdit,
        enableDelete
    }) => ({
        // Correctly parse Boolean props
        enableExport: Boolean(enableExport),
        enableBulkDelete: Boolean(enableBulkDelete),
        enableEdit: Boolean(enableEdit),
        enableDelete: Boolean(enableDelete),

        // Reactive state
        items: [],
        currentPage: 1,
        totalPages: 1,
        search: '',
        searchTimeout: null, // Debounce for search
        sortColumn: '',
        sortDirection: 'asc',
        selected: [],
        loading: false,
        showColumnManager: false,
        columns: columns,
        exportUrl: exportUrl,
        baseUrl: baseUrl,

        // Initialization
        init() {
            // Prevent reinitializing the same instanceKey
            if (window.initializedInstances.includes(instanceKey)) {
                // console.warn(`⚠️ Skipping duplicate initialization for instance: ${instanceKey}`);
                return;
            }
            window.initializedInstances.push(instanceKey);
            //console.log(`✅ Initializing DataTable for instance: ${instanceKey}`);
            this.loadColumnPreferences(); // Load column visibility preferences
            this.fetchData(); // Fetch initial data
        },

        // Generate page numbers for pagination
        pagesList() {
            return Array.from({ length: this.totalPages }, (_, i) => i + 1);
        },

        // Navigate to a specific page
        goToPage(pageNum) {
            if (pageNum === this.currentPage) return;
            this.currentPage = pageNum;
            this.fetchData();
        },

        // Go to the previous page
        prevPage() {
            if (this.currentPage > 1) {
                this.currentPage--;
                this.fetchData();
            }
        },

        // Go to the next page
        nextPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage++;
                this.fetchData();
            }
        },

        // Trigger search and reload data with debounce
        searchItems() {
            // Clear previous timeout if any
            if (this.searchTimeout) {
                clearTimeout(this.searchTimeout);
            }
            // Set debounce timeout (300ms)
            this.searchTimeout = setTimeout(() => {
                if (this.search.trim().length <= 2 && this.search.trim() !== '') {
                    // console.warn('Search term too short. Ignoring request.');
                    return;
                }
                this.currentPage = 1;
                this.fetchData();
            }, 300);
        },

        // Sort data by a specific column
        sortBy(column) {
            if (this.sortColumn === column) {
                this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                this.sortColumn = column;
                this.sortDirection = 'asc';
            }
            this.currentPage = 1;
            this.fetchData();
        },

        // Fetch data from the server using Axios
        fetchData() {
            if (!dataUrl || dataUrl === 'undefined') {
                console.error(`❗ Error: dataUrl is undefined for instance "${instanceKey}".`);
                return;
            }

            const params = {
                search: this.search || '',
                sort: this.sortColumn || 'id',
                direction: this.sortDirection || 'asc',
                page: this.currentPage || 1
            };

            this.loading = true;
            axios
                .get(dataUrl, { params })
                .then(res => {
                    const data = res.data;
                    this.items = data.data || [];
                    this.currentPage = data.current_page || 1;
                    this.totalPages = data.last_page || 1;
                })
                .catch(error => {
                    console.error('❗ API Request Error:', error);
                })
                .finally(() => {
                    this.loading = false;
                });
        },

        // Delete a single item (AJAX request)
        deleteItem(id) {
            if (!confirm('Are you sure you want to delete this item?')) return;
            axios.delete(`${baseUrl}/${id}`).then(() => this.fetchData());
        },

        // Bulk delete selected items (AJAX request)
        deleteSelected() {
            if (!confirm(`Delete ${this.selected.length} selected items?`)) return;
            const url = bulkUrl ? bulkUrl : `${baseUrl}/bulk-delete`;
            axios.post(url, { ids: this.selected }).then(() => {
                this.selected = [];
                this.fetchData();
            });
        },

        // Add this computed property to Alpine data
        instanceKeyWithScope() {
            return this.instanceKey || 'default';
        },

        // Load column visibility preferences scoped to instanceKey with fallback to fillable
        loadColumnPreferences() {
            const savedColumns = JSON.parse(localStorage.getItem(`${this.instanceKey}_datatable_columns`));

            if (savedColumns) {
                // Load saved preferences if they exist
                this.columns.forEach(col => {
                    if (savedColumns[col.key] !== undefined) {
                        col.visible = savedColumns[col.key];
                    }
                });
            } else {
                // No saved preferences, fallback to default 'fillable' visibility
                this.columns.forEach(col => {
                    col.visible = col.visible !== undefined ? col.visible : true;
                });

                // Save initial preferences for future loads to prevent overriding
                this.saveColumnPreferences();
            }
        },
        // Save column visibility preferences scoped to instanceKey
        saveColumnPreferences() {
            const columnPrefs = this.columns.reduce((acc, col) => {
                acc[col.key] = col.visible;
                return acc;
            }, {});

            localStorage.setItem(`${this.instanceKey}_datatable_columns`, JSON.stringify(columnPrefs));
        },

        // Toggle column visibility and save to localStorage
        toggleColumnVisibility(colKey) {
            const col = this.columns.find(c => c.key === colKey);
            if (col) {
                col.visible = !col.visible;
                this.saveColumnPreferences();
            }
        }
    }));
    // Get column visibility scoped to instanceKey
    function getColumnVisibility(instanceKey, colKey) {
        const storedValue = localStorage.getItem(`${instanceKey}_col_${colKey}`);
        return storedValue === null ? true : storedValue === 'true';
    }

    // Save column visibility preferences to localStorage
    function setColumnVisibility(instanceKey, colKey, isVisible) {
        localStorage.setItem(`${instanceKey}_col_${colKey}`, isVisible);
    }
});



Alpine.plugin(persist)
Alpine.start();