import { derived, writable } from 'svelte/store';

const PERIOD_STORAGE_KEY = 'headroom_selected_period';

function getCurrentMonthPeriod(): string {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  return `${year}-${month}`;
}

function isPeriod(value: string | null): value is string {
  if (value === null) return false;
  return /^\d{4}-(0[1-9]|1[0-2])$/.test(value);
}

function getInitialPeriod(): string {
  if (typeof localStorage === 'undefined') return getCurrentMonthPeriod();

  const stored = localStorage.getItem(PERIOD_STORAGE_KEY);
  return isPeriod(stored) ? stored : getCurrentMonthPeriod();
}

const selectedPeriodWritable = writable<string>(getInitialPeriod());

if (typeof localStorage !== 'undefined') {
  selectedPeriodWritable.subscribe((value) => {
    localStorage.setItem(PERIOD_STORAGE_KEY, value);
  });
}

export const selectedPeriod = {
  subscribe: selectedPeriodWritable.subscribe
};

export const selectedMonth = derived(selectedPeriodWritable, ($period) => {
  const [year, month] = $period.split('-').map(Number);
  return { year, month };
});

export const selectedDate = derived(selectedPeriodWritable, ($period) => {
  const [year, month] = $period.split('-').map(Number);
  return new Date(year, month - 1, 1);
});

export function setPeriod(period: string): void {
  if (!isPeriod(period)) return;
  selectedPeriodWritable.set(period);
}

export function previousMonth(): void {
  selectedPeriodWritable.update((current) => {
    const [year, month] = current.split('-').map(Number);
    const date = new Date(year, month - 2, 1);
    const nextYear = date.getFullYear();
    const nextMonth = String(date.getMonth() + 1).padStart(2, '0');
    return `${nextYear}-${nextMonth}`;
  });
}

export function nextMonth(): void {
  selectedPeriodWritable.update((current) => {
    const [year, month] = current.split('-').map(Number);
    const date = new Date(year, month, 1);
    const nextYear = date.getFullYear();
    const nextMonth = String(date.getMonth() + 1).padStart(2, '0');
    return `${nextYear}-${nextMonth}`;
  });
}

export function currentMonth(): void {
  selectedPeriodWritable.set(getCurrentMonthPeriod());
}
