import AirDatepicker from 'air-datepicker';
import 'air-datepicker/air-datepicker.css';
import localeEn from 'air-datepicker/locale/en';
import { isPremiumUser } from '../utils/premium';

const { __ } = wp.i18n;

class SharedDateRangeSelector {
    constructor(store) {
        this.store = store;
        this.dateRangePicker = null;
        this.dateFormat = linkcentral_insights_data.date_format || 'MM/dd/yyyy';
        this.isPremium = isPremiumUser();
        this.skipNextLoad = false;
        this.currentPreset = null;

        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');
    }

    triggerInitialLoad() {
        const defaultRange = this.getDateRange(7);
        this.store.setPeriod({
            preset: '7',
            formattedStartDate: defaultRange.formattedStartDate,
            formattedEndDate: defaultRange.formattedEndDate,
        });
    }

    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.publishPeriod(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;
        }

        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;
        const range = this.getDateRange(days);

        if (this.dateRangePicker) {
            this.dateRangePicker.clear({ silent: true });
            this.dateRangePicker.selectDate([range.startDate, range.endDate], {
                silent: true,
            });
        }

        this.publishPeriod(range.startDate, range.endDate, days.toString());
    }

    handlePresetSelection(timeframe) {
        if (timeframe === 'since_start') {
            if (this.dateRangePicker) {
                this.dateRangePicker.clear({ silent: true });
            }
            
            return;
        }

        this.handleQuickSelect(parseInt(timeframe, 10));
    }

    publishPeriod(startDate, endDate, preset) {
        this.store.setPeriod({
            preset,
            formattedStartDate: this.formatDateForAPI(startDate),
            formattedEndDate: this.formatDateForAPI(endDate),
        });
    }

    updateDateRange(startDate, endDate, preset = 'custom', silent = false) {
        if (this.dateRangePicker) {
            this.skipNextLoad = true;
            this.dateRangePicker.selectDate([startDate, endDate], {
                silent: true,
            });
            this.dateRangePicker.setViewDate(startDate);
        }

        this.setDateRangeLabel(preset);

        if (!silent) {
            this.publishPeriod(startDate, endDate, preset);
        }
    }

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

    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;
