import { EntrySource } from 'src/types/timeTracking';
import type { DaySummary, PairedEntry } from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { processHoursForDisplay } from 'src/utils/timeTracking';

type Params = {
  autoCloseMode?: DaySummary['autoCloseMode'];
  startEntry: PairedEntry['start'];
  endEntry: PairedEntry['end'];
};

export const useAutocloseDescription = ({
  autoCloseMode,
  startEntry,
  endEntry,
}: Params) => {
  const { t } = useLokaliseTranslation([
    'time_tracker',
    'time_tracking_common',
  ]);

  const autoClosed = endEntry?.source === EntrySource.AUTO_CLOSE;
  const autoCloseFallback = endEntry?.autoCloseFallback;

  let description: string | undefined;

  if (autoClosed) {
    const durationInMinutes =
      startEntry?.time && endEntry?.time
        ? Math.round(
            (new Date(endEntry.time).getTime() -
              new Date(startEntry.time).getTime()) /
              (1000 * 60),
          )
        : 0;
    if (autoCloseFallback != null) {
      const totalHours = Math.round(durationInMinutes / 60);
      description = t('autoclose_warning_fallback', { count: totalHours });
    } else {
      switch (autoCloseMode) {
        case 'FIXED_HOURS': {
          const { hours, minutes } = processHoursForDisplay(
            durationInMinutes / 60,
          );
          description = t('autoclose_warning_fixed_hours', {
            duration: t('time_tracking_common:hours_and_minutes_abbreviated', {
              hours,
              minutes,
            }),
          });
          break;
        }
        case 'SCHEDULED_HOURS':
          description = t('autoclose_warning_scheduled_hours');
          break;
        case 'END_OF_WORKDAY':
          description = t('autoclose_warning_end_of_workday');
          break;
        // TODO: ALERT_ONLY mode is not yet contemplated — falls through to generic warning intentionally
        case 'ALERT_ONLY':
        default:
          description = t('autoclose_warning');
      }
    }
  }

  return { autoClosed, description };
};
