import { useState, useCallback } from 'react';
import { Shift } from '../types/shift';

interface UseShiftSelectionReturn {
  selectionMode: boolean;
  setSelectionMode: (mode: boolean) => void;
  selectedShifts: Set<number>;
  toggleShiftSelection: (shiftId: number) => void;
  selectAllDay: (shifts: Shift[], targetDate: string) => void;
  selectAllWeek: (shifts: Shift[]) => void;
  deselectAll: () => void;
}

export function useShiftSelection(): UseShiftSelectionReturn {
  const [selectionMode, setSelectionMode] = useState(false);
  const [selectedShifts, setSelectedShifts] = useState<Set<number>>(new Set());

  const toggleShiftSelection = useCallback((shiftId: number) => {
    setSelectedShifts((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(shiftId)) {
        newSet.delete(shiftId);
      } else {
        newSet.add(shiftId);
      }
      return newSet;
    });
  }, []);

  const selectAllDay = useCallback((shifts: Shift[], targetDate: string) => {
    const shiftsByDate: Record<string, Shift[]> = {};
    shifts.forEach((shift) => {
      if (!shiftsByDate[shift.zs_date]) {
        shiftsByDate[shift.zs_date] = [];
      }
      shiftsByDate[shift.zs_date].push(shift);
    });

    const shiftsForDay = shiftsByDate[targetDate] || [];
    const shiftIds = shiftsForDay.map((s) => s.zs_id);
    setSelectedShifts(new Set(shiftIds));
    setSelectionMode(true);
  }, []);

  const selectAllWeek = useCallback((shifts: Shift[]) => {
    const allShiftIds = shifts.map((s) => s.zs_id);
    setSelectedShifts(new Set(allShiftIds));
    setSelectionMode(true);
  }, []);

  const deselectAll = useCallback(() => {
    setSelectedShifts(new Set());
    setSelectionMode(false);
  }, []);

  return {
    selectionMode,
    setSelectionMode,
    selectedShifts,
    toggleShiftSelection,
    selectAllDay,
    selectAllWeek,
    deselectAll,
  };
}

export default useShiftSelection;
