import {
    addDays,
    sameDay,
    startOfDay,
    startOfMonth,
    startOfWeekMonday,
    weekContains,
} from '../services/dateUtils.js';

export const CALENDAR_MONTHS_LONG = [
    'Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec',
    'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień',
];

export const CALENDAR_MONTHS_SHORT = [
    'sty', 'lut', 'mar', 'kwi', 'maj', 'cze',
    'lip', 'sie', 'wrz', 'paź', 'lis', 'gru',
];

export const CALENDAR_WEEKDAYS_SHORT = ['pn', 'wt', 'śr', 'cz', 'pt', 'so', 'nd'];
export const CALENDAR_DAY_ATTR = 'data-calendar-day';
export const CALENDAR_HANDLE_CLASS = 'block h-1 w-10 rounded-full bg-[#6d6c67]/75';

function getCalendarDayHTML(day, meta, dayState, dayAttr, theme = {}) {
    const { mode, selectedDate } = meta;
    const isSelected = selectedDate && sameDay(day, selectedDate);
    const showIndicator = !!dayState.showIndicator;
    const isDisabled = !!dayState.disabled;
    const isDimmed = !!dayState.dimmed && !isSelected;
    const defaultBg = '#2f2f2d';
    const defaultBorder = '#444442';
    const defaultText = '#d7d2c8';

    let bg;
    let borderColor;
    let text;
    let borderClass = 'border';

    if (isSelected) {
        bg = theme.selectedBg || '#23221e';
        borderColor = theme.selectedBorder || '#787876';
        text = theme.selectedText || '#f2efe8';
    } else if (isDimmed) {
        bg = theme.dimmedBg ?? theme.bg ?? defaultBg;
        text = theme.dimText || '#7d7a74';
        borderClass = 'border-0';
    } else {
        bg = theme.bg || defaultBg;
        borderColor = theme.border || defaultBorder;
        text = theme.text || defaultText;
    }

    const dot = isSelected ? (theme.selectedDot || '#f2efe8') : (theme.dot || '#a59f92');
    const opacity = isDimmed ? String(theme.dimOpacity ?? 0.72) : '1';
    const borderStyle = isDimmed ? 'border:none;' : `border-color:${borderColor};`;
    const outerClass = `${mode === 'month' ? 'mx-auto ' : ''}flex h-[2.05rem] w-full min-w-0 max-w-full items-center justify-center rounded-full ${borderClass} text-xs font-medium transition-colors leading-tight overflow-hidden`;
    const innerClass = mode === 'month'
        ? 'relative flex h-full w-full flex-col items-center justify-center'
        : 'relative flex h-full w-full items-center justify-center';
    const dotBottom = mode === 'month' ? '0.24rem' : '0.2rem';
    const tagName = isDisabled ? 'div' : 'button';
    const buttonAttrs = isDisabled ? '' : ` type="button" ${dayAttr}="${day.getTime()}"`;

    return `
        <${tagName}${buttonAttrs}
            class="${outerClass}"
            style="background:${bg};${borderStyle}color:${text};opacity:${opacity};">
            <span class="${innerClass}">
                <span class="text-[13px] font-semibold leading-none ${showIndicator ? '-translate-y-[0.18rem]' : ''}">${day.getDate()}</span>
                ${showIndicator
        ? `<span class="absolute left-1/2 w-1 h-1 -translate-x-1/2 rounded-full opacity-75" style="bottom:${dotBottom};background:${dot};" aria-hidden="true"></span>`
        : ''}
            </span>
        </${tagName}>
    `;
}

function getMonthCells(monthAnchor) {
    const first = startOfMonth(monthAnchor);
    const startGrid = startOfWeekMonday(first);
    const cells = [];
    for (let i = 0; i < 42; i++) cells.push(addDays(startGrid, i));
    while (cells.length > 35 && cells.slice(-7).every((day) => day.getMonth() !== first.getMonth())) {
        cells.splice(-7);
    }
    return { cells, month: first.getMonth() };
}

function getDayState(day, meta, resolveDayState) {
    if (typeof resolveDayState !== 'function') {
        return {
            disabled: false,
            dimmed: meta.mode === 'month' && !meta.inCurrentMonth,
            showIndicator: false,
        };
    }

    const resolved = resolveDayState(day, meta) || {};
    return {
        disabled: !!resolved.disabled,
        dimmed: !!resolved.dimmed,
        showIndicator: !!resolved.showIndicator,
    };
}

export function createCalendarWeekdayHeaderHTML(labels = CALENDAR_WEEKDAYS_SHORT, {
    wrapperClass = 'grid grid-cols-7 gap-1.5 text-center text-[8px] font-medium text-gray-400 uppercase tracking-wide mb-1 leading-none',
} = {}) {
    return `
        <div class="${wrapperClass}">
            ${labels.map((label) => `<div>${label}</div>`).join('')}
        </div>
    `;
}

export function createCalendarTopbarHTML({
    prevId,
    todayId,
    nextId,
    wrapperClass = 'px-4 pt-4 pb-3 flex items-center justify-end',
    controlsStyle = 'background:#2f2f2d;border-color:#444442;',
    navButtonClass = 'shrink-0 w-7 h-full flex items-center justify-center rounded-full border-0 bg-transparent text-[#d7d2c8] transition-colors',
    todayButtonActiveClass = 'h-full shrink-0 inline-flex min-w-[5.75rem] max-w-[9rem] items-center justify-center rounded-full bg-transparent px-1.5 text-[10px] font-semibold leading-none tabular-nums text-[#d7d2c8] active:bg-transparent whitespace-nowrap',
    todayButtonDimClass = 'h-full shrink-0 inline-flex items-center justify-center rounded-full px-2 text-[10px] font-semibold leading-none text-[#7d7a74] cursor-default',
}) {
    return `
        <div class="${wrapperClass}">
            <div class="flex h-[2.05rem] min-w-0 max-w-[min(100%,20rem)] items-center gap-px rounded-full border px-0.5" style="${controlsStyle}">
                <button type="button" id="${prevId}" class="${navButtonClass}" aria-label="Poprzedni okres">
                    <i class="fas fa-chevron-left text-[10px]" aria-hidden="true"></i>
                </button>
                <button type="button" id="${todayId}"
                        class="${todayButtonActiveClass}"
                        data-cal-active-class="${todayButtonActiveClass}"
                        data-cal-dim-class="${todayButtonDimClass}">
                </button>
                <button type="button" id="${nextId}" class="${navButtonClass}" aria-label="Następny okres">
                    <i class="fas fa-chevron-right text-[10px]" aria-hidden="true"></i>
                </button>
            </div>
        </div>
    `;
}

export function formatCalendarMonthYear(date) {
    return `${CALENDAR_MONTHS_LONG[date.getMonth()]} ${date.getFullYear()}`;
}

export function formatCalendarSelectedDate(date) {
    return `${date.getDate()} ${CALENDAR_MONTHS_SHORT[date.getMonth()]} ${date.getFullYear()}`;
}

export function isCalendarOnToday(mode, weekStart, monthAnchor, selectedDate) {
    const today = startOfDay(new Date());
    if (!sameDay(selectedDate, today)) return false;
    if (mode === 'week') return weekContains(weekStart, today);
    return startOfMonth(monthAnchor).getTime() === startOfMonth(today).getTime();
}

/**
 * Środkowy przycisk pokazuje wybraną datę; działa jak „Dziś” (skok do bieżącego okresu).
 * Styl pozostaje jak aktywny — bez wyciszania przy isOnToday.
 */
export function syncCalendarTodayButton(buttonEl, isOnToday, selectedDate, options = {}) {
    if (!buttonEl) return;
    const {
        ariaLabelGo = 'Przejdź do dzisiejszego dnia',
        ariaLabelCurrent = 'Widok jest ustawiony na bieżący okres',
    } = options;
    const active = buttonEl.dataset.calActiveClass
        || 'h-full shrink-0 inline-flex min-w-[5.75rem] max-w-[9rem] items-center justify-center rounded-full bg-transparent px-1.5 text-[10px] font-semibold leading-none tabular-nums text-[#d7d2c8] active:bg-transparent whitespace-nowrap';
    if (selectedDate != null) {
        buttonEl.textContent = formatCalendarSelectedDate(selectedDate);
    }
    buttonEl.className = active;
    buttonEl.removeAttribute('disabled');
    buttonEl.setAttribute('aria-disabled', isOnToday ? 'true' : 'false');
    buttonEl.setAttribute('aria-label', isOnToday ? ariaLabelCurrent : ariaLabelGo);
}

export function renderCalendarGrid({
    gridEl,
    mode,
    anchorDate,
    selectedDate,
    resolveDayState,
    dayAttr = CALENDAR_DAY_ATTR,
    theme,
}) {
    if (!gridEl) return;

    if (mode === 'week') {
        const weekStart = startOfWeekMonday(anchorDate);
        const cells = [];
        for (let i = 0; i < 7; i++) {
            const day = addDays(weekStart, i);
            const meta = {
                mode,
                selectedDate,
                inCurrentMonth: true,
            };
            cells.push(getCalendarDayHTML(day, meta, getDayState(day, meta, resolveDayState), dayAttr, theme));
        }
        gridEl.innerHTML = cells.join('');
        return;
    }

    const { cells, month } = getMonthCells(anchorDate);
    gridEl.innerHTML = cells.map((day) => {
        const meta = {
            mode,
            selectedDate,
            inCurrentMonth: day.getMonth() === month,
        };
        return getCalendarDayHTML(day, meta, getDayState(day, meta, resolveDayState), dayAttr, theme);
    }).join('');
}

export function renderCollapsibleCalendar({
    weekGridEl,
    monthGridEl,
    weekAnchorDate,
    monthAnchorDate,
    selectedDate,
    resolveDayState,
    dayAttr = CALENDAR_DAY_ATTR,
}) {
    renderCalendarGrid({
        gridEl: weekGridEl,
        mode: 'week',
        anchorDate: weekAnchorDate,
        selectedDate,
        resolveDayState,
        dayAttr,
    });
    renderCalendarGrid({
        gridEl: monthGridEl,
        mode: 'month',
        anchorDate: monthAnchorDate,
        selectedDate,
        resolveDayState,
        dayAttr,
    });
}

export function syncCollapsibleCalendarMode({
    mode,
    weekWrapEl,
    monthWrapEl,
    handleEl,
    activePaddingBottom = '0.75rem',
    weekMaxHeight = '10rem',
    monthMaxHeight = '17.25rem',
}) {
    if (weekWrapEl) {
        weekWrapEl.style.maxHeight = mode === 'week' ? weekMaxHeight : '0';
        weekWrapEl.style.opacity = mode === 'week' ? '1' : '0';
        weekWrapEl.style.paddingBottom = mode === 'week' ? activePaddingBottom : '0';
    }
    if (monthWrapEl) {
        monthWrapEl.style.maxHeight = mode === 'month' ? monthMaxHeight : '0';
        monthWrapEl.style.opacity = mode === 'month' ? '1' : '0';
        monthWrapEl.style.paddingBottom = mode === 'month' ? activePaddingBottom : '0';
    }
    if (handleEl) handleEl.className = CALENDAR_HANDLE_CLASS;
}

export function bindCalendarDayClicks(containerEl, onSelect, dayAttr = CALENDAR_DAY_ATTR) {
    if (!containerEl || typeof onSelect !== 'function') return;
    containerEl.addEventListener('click', (event) => {
        const button = event.target.closest(`[${dayAttr}]`);
        if (!button || !containerEl.contains(button)) return;
        const ts = Number(button.getAttribute(dayAttr));
        if (!Number.isFinite(ts)) return;
        onSelect(new Date(ts), button, event);
    });
}
