import { Controller } from 'stimulus';

export default class extends Controller {
    static targets = ['input'];

    today(event) {
        event?.preventDefault?.();

        const today = this.startOfDay(new Date());
        this.setRange(today, today);
    }

    tomorrow(event) {
        event?.preventDefault?.();

        const tomorrow = this.addDays(this.startOfDay(new Date()), 1);
        this.setRange(tomorrow, tomorrow);
    }

    setRange(startDate, endDate) {
        const input = this.inputTarget;
        const formattedStart = this.formatDate(startDate);
        const formattedEnd = this.formatDate(endDate);
        const value = `${formattedStart} - ${formattedEnd}`;

        // If daterangepicker is attached, keep it in sync.
        if (typeof $ !== 'undefined') {
            const picker = $(input).data('daterangepicker');
            if (picker) {
                picker.setStartDate(formattedStart);
                picker.setEndDate(formattedEnd);

                // Ensure UI is refreshed for both calendars & input.
                if (typeof picker.updateCalendars === 'function') {
                    picker.updateCalendars();
                }
                if (typeof picker.updateView === 'function') {
                    picker.updateView();
                }
            }
        }

        input.value = value;
        input.dispatchEvent(new Event('change', { bubbles: true }));

        const form = this.element.closest('form');
        if (form) {
            if (typeof form.requestSubmit === 'function') {
                form.requestSubmit();
            } else {
                form.submit();
            }
        }
    }

    startOfDay(date) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate());
    }

    addDays(date, days) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
    }

    formatDate(date) {
        const dd = String(date.getDate()).padStart(2, '0');
        const mm = String(date.getMonth() + 1).padStart(2, '0');
        const yyyy = String(date.getFullYear());
        return `${dd}.${mm}.${yyyy}`;
    }
}

