import { useState } from 'react';

import {
  addMonths,
  endOfMonth,
  format,
  isAfter,
  startOfMonth,
  subMonths,
} from 'date-fns';

import { useAuth } from 'src/contexts/JWTContext';
import { useGetUserDaySummaries } from 'src/hooks/queryHooks/timeTracking';

export const useTimeHistory = () => {
  const { user } = useAuth();
  const [currentMonth, setCurrentMonth] = useState(() =>
    startOfMonth(new Date()),
  );

  const startDate = format(currentMonth, 'yyyy-MM-dd');
  const endDate = format(endOfMonth(currentMonth), 'yyyy-MM-dd');

  const userId = user?.id ?? 0;

  const { registers, isFetching } = useGetUserDaySummaries(
    {
      userIds: String(userId),
      startDate,
      endDate,
    },
    { enabled: userId > 0 },
  );

  const latestAllowedMonth = startOfMonth(new Date());

  const handlePrevMonth = () =>
    setCurrentMonth(prev => startOfMonth(subMonths(prev, 1)));

  const handleNextMonth = () =>
    setCurrentMonth(prev => {
      const next = startOfMonth(addMonths(prev, 1));
      return isAfter(next, latestAllowedMonth) ? prev : next;
    });

  const nextMonthDisabled = !isAfter(latestAllowedMonth, currentMonth);

  const daySummaries = registers?.[0]?.daySummaries ?? [];

  return {
    daySummaries,
    isFetching,
    currentMonth,
    handlePrevMonth,
    handleNextMonth,
    nextMonthDisabled,
  };
};
