import AirDatepicker from 'air-datepicker';
import 'air-datepicker/air-datepicker.css';
import localeEn from 'air-datepicker/locale/en';

// Import WordPress i18n function
const { __ } = wp.i18n;

class SharedDateRangeSelector {
    constructor() {
        this.dateRangePicker = null;
        this.dateFormat = linkcentral_insights_data.date_format || 'MM/dd/yyyy';
        this.isPremium = linkcentral_insights_data.can_use_premium_code__premium_only === '1';
        this.skipNextLoad = false; // Simple flag to prevent duplicate loading
        this.currentPreset = null; // Track current preset
        this.listeners = []; // Array to store event listeners
        
        // Preset labels mapping
        this.presetLabels = {
            '7': __('Last 7 Days', 'linkcentral'),
            '30': __('Last 30 Days', 'linkcentral'),
            '365': __('Last Year', 'linkcentral'),
            'since_start': __('Since Start', 'linkcentral'),
            'custom': __('Custom Range', 'linkcentral')
        };
    }

    init() {
        this.initDatePickers();
        this.setupDateRangeLabel();
        this.setDateRangeLabel('7'); // Set initial label
    }

    // Method to trigger initial data load after all components are ready
    triggerInitialLoad() {
        // Set initial date range to last 7 days
        const defaultRange = this.getDateRange(7);
        this.notifyListeners(defaultRange.startDate, defaultRange.endDate, '7');
    }

    // Event system for notifying components about date range changes
    addEventListener(callback) {
        this.listeners.push(callback);
    }

    removeEventListener(callback) {
        const index = this.listeners.indexOf(callback);
        if (index > -1) {
            this.listeners.splice(index, 1);
        }
    }

    notifyListeners(startDate, endDate, preset = 'custom') {
        this.listeners.forEach(callback => {
            callback({
                startDate,
                endDate,
                preset,
                formattedStartDate: this.formatDateForAPI(startDate),
                formattedEndDate: this.formatDateForAPI(endDate)
            });
        });
    }

    initDatePickers() {
        const dateRangeInput = document.getElementById('linkcentral-datepicker');
        if (!dateRangeInput) {
            console.error('Date range input not found');
            return;
        }

        const defaultRange = this.getDateRange(7);
        
        this.dateRangePicker = new AirDatepicker(dateRangeInput, {
            range: true,
            multipleDates: false,
            toggleSelected: false,
            locale: localeEn,
            buttons: this.createQuickSelectButtons(),
            multipleDatesSeparator: ' - ',
            selectedDates: [defaultRange.startDate, defaultRange.endDate],
            dateFormat: this.dateFormat,
            firstDay: Number(linkcentral_insights_data.start_of_week),
            onSelect: ({datepicker}) => {
                if (this.skipNextLoad) {
                    this.skipNextLoad = false;
                    return;
                }
                
                const selectedDates = datepicker.selectedDates;
                if (selectedDates.length !== 2) return;
                
                this.setDateRangeLabel('custom');
                this.notifyListeners(selectedDates[0], selectedDates[1], 'custom');
            },
            autoClose: true
        });
    }

    createQuickSelectButtons() {
        return [
            {
                content: __('Since start', 'linkcentral') + (!this.isPremium ? ` (${__('Premium only', 'linkcentral')})` : ''),
                onClick: () => {
                    if (this.isPremium) {
                        this.skipNextLoad = true;
                        this.setDateRangeLabel('since_start');
                        this.handlePresetSelection('since_start');
                    }
                },
                className: `linkcentral-datepicker-button${!this.isPremium ? ' disabled' : ''}`
            },
            {
                content: __('Last 7 days', 'linkcentral'),
                onClick: () => {
                    this.setDateRangeLabel('7');
                    this.handleQuickSelect(7);
                },
                className: 'linkcentral-datepicker-button'
            },
            {
                content: __('Last 30 days', 'linkcentral'),
                onClick: () => {
                    this.setDateRangeLabel('30');
                    this.handleQuickSelect(30);
                },
                className: 'linkcentral-datepicker-button'
            },
            {
                content: __('Last year', 'linkcentral'),
                onClick: () => {
                    this.setDateRangeLabel('365');
                    this.handleQuickSelect(365);
                },
                className: 'linkcentral-datepicker-button'
            }
        ];
    }

    setupDateRangeLabel() {
        const dateRangeInput = document.getElementById('linkcentral-datepicker');
        if (!dateRangeInput) return;

        // Create label element if it doesn't exist
        let labelElement = document.getElementById('linkcentral-date-range-label');
        if (!labelElement) {
            labelElement = document.createElement('span');
            labelElement.id = 'linkcentral-date-range-label';
            labelElement.className = 'linkcentral-date-range-label';
            labelElement.style.cssText = 'display: inline-block; margin-right: 10px; font-weight: bold; font-size: 12px; color: #666;';
            dateRangeInput.parentNode.insertBefore(labelElement, dateRangeInput);
        }
    }

    setDateRangeLabel(preset) {
        this.currentPreset = preset;
        const labelElement = document.getElementById('linkcentral-date-range-label');
        if (labelElement && this.presetLabels[preset]) {
            labelElement.textContent = this.presetLabels[preset];
        }
    }

    getDateRange(days = 7) {
        const endDate = new Date();
        const startDate = new Date();
        
        if (days === 365) {
            startDate.setFullYear(endDate.getFullYear() - 1);
            startDate.setDate(startDate.getDate() + 1);
        } else {
            startDate.setDate(endDate.getDate() - (days - 1));
        }
        
        return {
            startDate,
            endDate,
            formattedStartDate: this.formatDateForAPI(startDate),
            formattedEndDate: this.formatDateForAPI(endDate)
        };
    }

    handleQuickSelect(days) {
        this.skipNextLoad = true; // Prevent duplicate load from datepicker update
        const range = this.getDateRange(days);

        // Update datepicker silently - ensure we reset any partial selection
        if (this.dateRangePicker) {
            // Force clear any previous selection state first
            this.dateRangePicker.clear({silent: true});
            
            // Set the new date range
            this.dateRangePicker.selectDate([range.startDate, range.endDate], {
                silent: true
            });
        }
        
        // Notify listeners
        this.notifyListeners(range.startDate, range.endDate, days.toString());
    }

    handlePresetSelection(timeframe) {
        if (timeframe === 'since_start') {
            // Clear any partial selection from the datepicker
            if (this.dateRangePicker) {
                this.dateRangePicker.clear({silent: true});
            }
            
            
            return;
        }

        this.handleQuickSelect(parseInt(timeframe));
    }

    updateDateRange(startDate, endDate, preset = 'custom') {
        if (this.dateRangePicker) {
            this.skipNextLoad = true; // Prevent duplicate load
            this.dateRangePicker.selectDate([startDate, endDate], {
                silent: true
            });
            this.dateRangePicker.setViewDate(startDate);
        }
        
        this.setDateRangeLabel(preset);
        this.notifyListeners(startDate, endDate, preset);
    }

    formatDateForAPI(date) {
        if (!date) return null;
        return date.toISOString().split('T')[0];
    }

    // Public methods for external components to get current state
    getCurrentDateRange() {
        if (this.dateRangePicker && this.dateRangePicker.selectedDates.length === 2) {
            return {
                startDate: this.dateRangePicker.selectedDates[0],
                endDate: this.dateRangePicker.selectedDates[1],
                preset: this.currentPreset,
                formattedStartDate: this.formatDateForAPI(this.dateRangePicker.selectedDates[0]),
                formattedEndDate: this.formatDateForAPI(this.dateRangePicker.selectedDates[1])
            };
        }
        return null;
    }

    getCurrentPreset() {
        return this.currentPreset;
    }
}

export default SharedDateRangeSelector; 