import { useQuery } from 'react-query';

import { logEvent } from 'src/config/amplitude';
import { type UseClockingInfoReturn } from 'src/components/dashboard/hooks/timeTracking';
import { useMarkingClockDrawer } from 'src/components/dashboard/MarkingClock/useMarkingClock';
import { timeTrackingKeys } from 'src/pages/dashboard/timeTracking/queries';
import { getTimeTrackingDaySummary } from 'src/services/timeTracking';
import { EventName } from 'src/types/amplitude';
import { EntryType } from 'src/types/timeTracking';
import {
  formatCompleteDecimalHours,
  parseDayScheduleStatus,
} from 'src/utils/timeTracking';
import { truncateTimeToHHMM } from '../constants';

export const useTimeTrack = (clockingInfo: UseClockingInfoReturn) => {
  const {
    clockTime,
    isClockRunning,
    isFetchingClockingInfo,
    isLoadingToggleClock,
    lastEntryStart,
    timeTrackingClockIsEnabled,
    toggleClockMutation,
    userTrackingSites,
  } = clockingInfo;

  const { data: daySummary } = useQuery(
    timeTrackingKeys.daySummary(),
    getTimeTrackingDaySummary,
    {
      enabled: timeTrackingClockIsEnabled,
      select: res => res.data,
      staleTime: Infinity,
    },
  );

  const userHasMultipleSites =
    userTrackingSites && userTrackingSites.length > 1;

  const { drawer, showMarkingClockDrawer } = useMarkingClockDrawer({
    toggleClockMutation,
    isLoadingToggleClock,
    entryType: isClockRunning ? EntryType.END : EntryType.START,
  });

  const handleToggle = () => {
    logEvent(EventName.TIME_TRACKING_CLOCK_OPENED, {});

    if (isClockRunning) {
      if (userHasMultipleSites) {
        showMarkingClockDrawer({
          lastEntrySite:
            userTrackingSites.find(
              site => site.id === lastEntryStart?.siteId,
            ) ?? null,
        });
      } else {
        toggleClockMutation({
          type: EntryType.END,
          siteId: lastEntryStart?.siteId ?? null,
          location: lastEntryStart?.location ?? null,
        });
      }
    } else {
      if (userHasMultipleSites) {
        showMarkingClockDrawer({ lastEntrySite: null });
      } else {
        toggleClockMutation({
          type: EntryType.START,
          siteId: userTrackingSites?.[0]?.id ?? null,
          location: userTrackingSites?.[0]?.location ?? null,
        });
      }
    }
  };

  const firstTimeSlot = daySummary?.daySummary?.timeSlots?.[0];
  const schedule = firstTimeSlot
    ? `${truncateTimeToHHMM(firstTimeSlot.startTime ?? '')} - ${truncateTimeToHHMM(firstTimeSlot.endTime ?? '')}`
    : undefined;

  const scheduledHours = daySummary?.daySummary?.scheduledHours;
  const programmedTime =
    scheduledHours != null && scheduledHours > 0
      ? formatCompleteDecimalHours(scheduledHours)
      : undefined;

  const todayDayStatus = daySummary?.daySummary
    ? parseDayScheduleStatus({
        holidays: daySummary.daySummary.holidays,
        timeOffRequests: daySummary.daySummary.timeOffRequests,
        isWorkday: daySummary.daySummary.isWorkday,
        scheduleSource: daySummary.daySummary.scheduleSource,
      })
    : undefined;

  const isTodayDayOff = todayDayStatus?.isScheduledDayOff ?? false;
  const todayHoliday = daySummary?.daySummary?.holidays?.[0];
  const todayTimeOff = daySummary?.daySummary?.timeOffRequests?.[0];

  return {
    workedTime: `${clockTime.hours} ${clockTime.minutes}`,
    workedSeconds: clockTime.seconds,
    schedule,
    programmedTime,
    isClockRunning,
    isInitialLoading: isFetchingClockingInfo,
    isLoading: isFetchingClockingInfo || isLoadingToggleClock,
    isTodayDayOff,
    todayHoliday,
    todayTimeOff,
    handleToggle,
    drawer,
    timeTrackingClockIsEnabled,
  };
};
