import { useState, useMemo, useCallback } from 'react';

export type TimeRangePreset =
  | 'today'
  | 'yesterday'
  | 'last7days'
  | 'last30days'
  | 'last90days'
  | 'thisMonth'
  | 'lastMonth'
  | 'thisYear'
  | 'custom';

export interface TimeRange {
  startDate: Date;
  endDate: Date;
  preset: TimeRangePreset;
}

export interface UseTimeRangeOptions {
  /** Initial preset (default: 'last7days') */
  initialPreset?: TimeRangePreset;
  /** Initial custom start date */
  initialStartDate?: Date;
  /** Initial custom end date */
  initialEndDate?: Date;
}

export interface UseTimeRangeReturn {
  /** Current time range */
  timeRange: TimeRange;
  /** Set time range by preset */
  setPreset: (preset: TimeRangePreset) => void;
  /** Set custom date range */
  setCustomRange: (startDate: Date, endDate: Date) => void;
  /** Formatted start date string (YYYY-MM-DD) */
  startDateString: string;
  /** Formatted end date string (YYYY-MM-DD) */
  endDateString: string;
  /** Human-readable label for current range */
  label: string;
}

function getPresetDates(preset: TimeRangePreset): { startDate: Date; endDate: Date } {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const endDate = new Date(today);

  switch (preset) {
    case 'today':
      return { startDate: today, endDate };

    case 'yesterday': {
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      return { startDate: yesterday, endDate: yesterday };
    }

    case 'last7days': {
      const startDate = new Date(today);
      startDate.setDate(startDate.getDate() - 6);
      return { startDate, endDate };
    }

    case 'last30days': {
      const startDate = new Date(today);
      startDate.setDate(startDate.getDate() - 29);
      return { startDate, endDate };
    }

    case 'last90days': {
      const startDate = new Date(today);
      startDate.setDate(startDate.getDate() - 89);
      return { startDate, endDate };
    }

    case 'thisMonth': {
      const startDate = new Date(today.getFullYear(), today.getMonth(), 1);
      return { startDate, endDate };
    }

    case 'lastMonth': {
      const startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1);
      const lastDay = new Date(today.getFullYear(), today.getMonth(), 0);
      return { startDate, endDate: lastDay };
    }

    case 'thisYear': {
      const startDate = new Date(today.getFullYear(), 0, 1);
      return { startDate, endDate };
    }

    case 'custom':
    default:
      return { startDate: today, endDate };
  }
}

function getPresetLabel(preset: TimeRangePreset): string {
  switch (preset) {
    case 'today':
      return 'Today';
    case 'yesterday':
      return 'Yesterday';
    case 'last7days':
      return 'Last 7 days';
    case 'last30days':
      return 'Last 30 days';
    case 'last90days':
      return 'Last 90 days';
    case 'thisMonth':
      return 'This month';
    case 'lastMonth':
      return 'Last month';
    case 'thisYear':
      return 'This year';
    case 'custom':
      return 'Custom range';
    default:
      return preset;
  }
}

function formatDate(date: Date): string {
  return date.toISOString().split('T')[0];
}

/**
 * Hook for managing time range selection in analytics dashboards
 */
export function useTimeRange(options: UseTimeRangeOptions = {}): UseTimeRangeReturn {
  const { initialPreset = 'last7days', initialStartDate, initialEndDate } = options;

  const [timeRange, setTimeRange] = useState<TimeRange>(() => {
    if (initialPreset === 'custom' && initialStartDate && initialEndDate) {
      return {
        startDate: initialStartDate,
        endDate: initialEndDate,
        preset: 'custom',
      };
    }
    const dates = getPresetDates(initialPreset);
    return { ...dates, preset: initialPreset };
  });

  const setPreset = useCallback((preset: TimeRangePreset) => {
    const dates = getPresetDates(preset);
    setTimeRange({ ...dates, preset });
  }, []);

  const setCustomRange = useCallback((startDate: Date, endDate: Date) => {
    setTimeRange({ startDate, endDate, preset: 'custom' });
  }, []);

  const startDateString = useMemo(() => formatDate(timeRange.startDate), [timeRange.startDate]);
  const endDateString = useMemo(() => formatDate(timeRange.endDate), [timeRange.endDate]);

  const label = useMemo(() => {
    if (timeRange.preset === 'custom') {
      return `${startDateString} - ${endDateString}`;
    }
    return getPresetLabel(timeRange.preset);
  }, [timeRange.preset, startDateString, endDateString]);

  return {
    timeRange,
    setPreset,
    setCustomRange,
    startDateString,
    endDateString,
    label,
  };
}
