/**
 * Hook for managing dashboard filters (date range, custom dates)
 */

import { useState, useCallback } from 'react';
import { DateRange } from '@/services/dashboard.service';

export function useDashboardFilters() {
  const [dateRange, setDateRange] = useState<DateRange>('all');
  const [customStartDate, setCustomStartDate] = useState<Date | undefined>(undefined);
  const [customEndDate, setCustomEndDate] = useState<Date | undefined>(undefined);
  const [showCustomDatePicker, setShowCustomDatePicker] = useState(false);

  const handleDateRangeChange = useCallback((value: string) => {
    const newRange = value as DateRange;
    setDateRange(newRange);
    if (newRange !== 'custom') {
      setCustomStartDate(undefined);
      setCustomEndDate(undefined);
      setShowCustomDatePicker(false);
    } else {
      setShowCustomDatePicker(true);
    }
  }, []);

  const handleApplyCustomDate = useCallback((onApply: (start: Date, end: Date) => void) => {
    if (customStartDate && customEndDate) {
      if (customStartDate > customEndDate) {
        // Swap dates if start is after end
        const temp = customStartDate;
        setCustomStartDate(customEndDate);
        setCustomEndDate(temp);
        onApply(customEndDate, temp);
      } else {
        onApply(customStartDate, customEndDate);
      }
      setShowCustomDatePicker(false);
    }
  }, [customStartDate, customEndDate]);

  const resetCustomDates = useCallback(() => {
    setCustomStartDate(undefined);
    setCustomEndDate(undefined);
    setShowCustomDatePicker(false);
    setDateRange('all');
  }, []);

  return {
    dateRange,
    customStartDate,
    customEndDate,
    showCustomDatePicker,
    setDateRange,
    setCustomStartDate,
    setCustomEndDate,
    setShowCustomDatePicker,
    handleDateRangeChange,
    handleApplyCustomDate,
    resetCustomDates,
  };
}

