import { useTheme } from '@material-hu/mui/styles';

import { type ShiftColor } from 'src/types/shifts';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  calculateTimeSpanInHours,
  parseHoursAndMinutesDisplay,
} from 'src/utils/timeTracking';

import { SHIFT_CARD_COLORS } from '../../../ShiftsTable/constants';

type ShiftDisplayInput = {
  color: string | null;
  timeSlots: { startTime: string; endTime: string }[];
};

/**
 * Shared shift display derivations used by every "shift card" rendered in
 * the rotation flow (selector items, day shift lines, etc.):
 *  - `colors`: palette tokens (background, accent border, text) for the
 *    shift's color (or the dayOff palette when `color` is null).
 *  - `totalHours`: sum of decimal hours across the shift's time slots.
 *  - `programmedDisplay`: localized "Xh Ym programadas" / "Xh programadas"
 *    string built from the total hours.
 */
export const useShiftDisplay = (shift: ShiftDisplayInput) => {
  const { t } = useLokaliseTranslation([
    'time_tracker',
    'time_tracking_common',
  ]);
  const theme = useTheme();

  const colors = SHIFT_CARD_COLORS(theme.palette)[
    (shift.color as ShiftColor) ?? 'dayOff'
  ];

  const totalHours = shift.timeSlots.reduce(
    (acc, slot) => acc + calculateTimeSpanInHours(slot.startTime, slot.endTime),
    0,
  );

  const programmedText = t('time_tracker:scheduled_f', { count: totalHours });
  const programmedDisplay = `${t(
    ...parseHoursAndMinutesDisplay(totalHours, true),
  )} ${programmedText}`;

  return {
    colors,
    totalHours,
    programmedDisplay,
  };
};
