import type { Dayjs } from 'dayjs';

import dayjs from 'dayjs';

import type { DashboardPeriod } from '../api';

/** 新版周期缓存 key（JSON 结构，支持自定义区间） */
const KEY_PERIOD_V2 = 'salesperson_dashboard_period_v2';
/** 旧版纯字符串 key，读取后自动迁移 */
const KEY_PERIOD_LEGACY = 'salesperson_dashboard_period';

const ALL_PERIOD_VALUES: DashboardPeriod[] = [
  'today',
  'last7days',
  'this_month',
  'last30days',
  'this_year',
  'last365days',
  'last_year',
  'custom',
];

export type PeriodFilterState = {
  period: DashboardPeriod;
  customRange?: [Dayjs, Dayjs];
};

function isValidPeriod(value: string): value is DashboardPeriod {
  return ALL_PERIOD_VALUES.includes(value as DashboardPeriod);
}

function parseCustomRange(start?: string, end?: string): [Dayjs, Dayjs] | null {
  if (!start || !end) return null;
  const rangeStart = dayjs(start);
  const rangeEnd = dayjs(end);
  if (!rangeStart.isValid() || !rangeEnd.isValid()) return null;
  return [rangeStart, rangeEnd];
}

/**
 * 从 localStorage 恢复周期筛选状态。
 * 兼容旧版纯字符串缓存，并自动迁移到 v2 JSON 格式。
 */
export function loadPeriodFilter(): PeriodFilterState {
  const rawV2 = localStorage.getItem(KEY_PERIOD_V2);
  if (rawV2) {
    try {
      const parsed = JSON.parse(rawV2) as { period?: string; start?: string; end?: string };
      if (parsed?.period && isValidPeriod(parsed.period)) {
        if (parsed.period === 'custom') {
          const customRange = parseCustomRange(parsed.start, parsed.end);
          if (customRange) {
            return { period: 'custom', customRange };
          }
          return { period: 'today' };
        }
        return { period: parsed.period };
      }
    } catch {
      // 解析失败则走默认
    }
  }

  const legacy = localStorage.getItem(KEY_PERIOD_LEGACY);
  if (legacy && isValidPeriod(legacy) && legacy !== 'custom') {
    const state: PeriodFilterState = { period: legacy };
    savePeriodFilter(state);
    localStorage.removeItem(KEY_PERIOD_LEGACY);
    return state;
  }

  return { period: 'today' };
}

/**
 * 持久化周期筛选状态，自定义区间仅存 YYYY-MM-DD 便于跨刷新恢复。
 */
export function savePeriodFilter(state: PeriodFilterState) {
  if (state.period === 'custom' && state.customRange) {
    const payload = {
      period: 'custom',
      start: state.customRange[0].format('YYYY-MM-DD'),
      end: state.customRange[1].format('YYYY-MM-DD'),
    };
    localStorage.setItem(KEY_PERIOD_V2, JSON.stringify(payload));
    return;
  }

  localStorage.setItem(KEY_PERIOD_V2, JSON.stringify({ period: state.period }));
}

export function defaultCustomRange(): [Dayjs, Dayjs] {
  return [dayjs().startOf('month'), dayjs()];
}
