import {
  type DayDetailHours,
  type DayDetailResponse,
  DayDetailScheduleSource,
  type TimeOffRequest,
} from 'src/types/timeTracking';
import { type LokaliseTFunction } from 'src/utils/i18n';
import { formatCompleteDecimalHours } from 'src/utils/timeTracking';

const getPermissionText = (
  timeOffRequest: TimeOffRequest,
  t: LokaliseTFunction,
): string | null => {
  const { consumptionType, fromTime, toTime, fromDate, toDate, hours } =
    timeOffRequest;

  if (consumptionType === 'HOURS' && fromTime && toTime) {
    return t('time_tracker:has_permission_time_range', {
      from: fromTime,
      to: toTime,
    });
  }

  if (fromDate && toDate && fromDate !== toDate) {
    return t('time_tracker:has_permission_period', {
      from: fromDate,
      to: toDate,
    });
  }

  if (hours != null) {
    return t('time_tracker:has_permission_hours', {
      time: formatCompleteDecimalHours(hours),
    });
  }

  return null;
};

export const checkIsRestDay = (dayDetail: DayDetailResponse): boolean =>
  !dayDetail.isWorkday &&
  dayDetail.schedule.source !== DayDetailScheduleSource.NONE &&
  dayDetail.holidays.length === 0;

export const getSubRowParts = (
  dayDetail: DayDetailResponse,
  t: LokaliseTFunction,
): { programmedText: string; contextText: string | null } => {
  const { hours, isWorkday, holidays, timeOffRequests } = dayDetail;
  const isRestDay = checkIsRestDay(dayDetail);

  if (isRestDay) {
    return {
      programmedText: t('time_tracker:day_off'),
      contextText: null,
    };
  }

  const programmedText = getProgrammedText(hours, t);

  if (holidays.length > 0) {
    if (!isWorkday) {
      return {
        programmedText: t('time_tracker:non_workable_holiday'),
        contextText: null,
      };
    }
    return {
      programmedText,
      contextText: t('time_tracker:workable_holiday'),
    };
  }

  const timeOff = timeOffRequests[0];
  if (timeOff) {
    return {
      programmedText,
      contextText: getPermissionText(timeOff, t),
    };
  }

  return { programmedText, contextText: null };
};

const getProgrammedText = (
  hours: DayDetailHours,
  t: LokaliseTFunction,
): string => {
  if (hours.estimated % 1 === 0) {
    return t('time_tracker:programmed_hour', { count: hours.estimated });
  }

  return t('time_tracker:programmed_time', {
    time: formatCompleteDecimalHours(hours.estimated),
  });
};
