/*
*  author: Yagnik Poshiya
*  organization: Webbrains Technologies Private Limited
*/

import type { ProjectAnalyticsDateRange } from '@/lib/project-analytics/project-analytics-types';

/**
 * Local `YYYY-MM-DD`, not `toISOString().slice(0,10)`.
 *
 * toISOString converts to UTC first, so late in the evening east of UTC — or
 * early morning west of it — "today" comes out as the wrong date.
 */
export function toLocalDateKey(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

export function parseLocalDateKey(key: string | null): Date | undefined {
  if (!key) return undefined;
  const parts = /^(\d{4})-(\d{2})-(\d{2})$/.exec(key);
  if (!parts) return undefined;
  return new Date(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]));
}

export type DateRangePreset = {
  id: string;
  label: string;
  build: () => ProjectAnalyticsDateRange;
};

function daysAgo(count: number): Date {
  const date = new Date();
  date.setDate(date.getDate() - count);
  return date;
}

export const DATE_RANGE_PRESETS: DateRangePreset[] = [
  { id: 'all', label: 'All time', build: () => ({ from: null, to: null }) },
  {
    id: 'today',
    label: 'Today',
    build: () => {
      const key = toLocalDateKey(new Date());
      return { from: key, to: key };
    },
  },
  {
    id: 'last7',
    label: 'Last 7 days',
    build: () => ({ from: toLocalDateKey(daysAgo(6)), to: toLocalDateKey(new Date()) }),
  },
  {
    id: 'last30',
    label: 'Last 30 days',
    build: () => ({ from: toLocalDateKey(daysAgo(29)), to: toLocalDateKey(new Date()) }),
  },
  {
    id: 'thisMonth',
    label: 'This month',
    build: () => {
      const now = new Date();
      return {
        from: toLocalDateKey(new Date(now.getFullYear(), now.getMonth(), 1)),
        to: toLocalDateKey(now),
      };
    },
  },
];

export function describeDateRange(range: ProjectAnalyticsDateRange, emptyLabel: string): string {
  if (!range.from && !range.to) return emptyLabel;
  const format = (key: string | null) => {
    const date = parseLocalDateKey(key);
    return date
      ? date.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' })
      : '…';
  };
  if (range.from && range.to) {
    return range.from === range.to ? format(range.from) : `${format(range.from)} – ${format(range.to)}`;
  }
  if (range.from) return `From ${format(range.from)}`;
  return `Until ${format(range.to)}`;
}
