import { isNil } from 'lodash-es';
import { type Theme } from '@material-hu/mui/styles';

import { GoalProgressChange } from '../types';

export const markerTypographySx = (theme: Theme) => ({
  fontSize: '12px',
  fontWeight: 400,
  color: theme.palette.new.text.neutral.lighter,
});

export const hasValue = (value: string | null | undefined): value is string =>
  !isNil(value) && value !== '';

export const computeMarkerPosition = (
  value: string,
  startingValue: string,
  objectiveValue: string,
): number => {
  const numValue = Number(value);
  const numStart = Number(startingValue);
  const numEnd = Number(objectiveValue);
  const range = numEnd - numStart;
  if (!Number.isFinite(range) || range === 0) return 0;
  const percent = ((numValue - numStart) / range) * 100;
  return Math.max(0, Math.min(100, percent));
};

export const getProgressValue = (
  isBinaryType: boolean,
  type: number | GoalProgressChange | null,
  value: number | string | null,
) => {
  if (isBinaryType) {
    return !isNil(type) ? (type as number) : null;
  }
  return !isNil(value) && value !== '' ? Number(value) : null;
};

export const getProgressType = (
  isBinaryType: boolean,
  type: number | GoalProgressChange | null,
  hasValue: boolean,
) => {
  if (isBinaryType) {
    return !isNil(type) ? GoalProgressChange.TOTAL_VALUE : null;
  }
  if (!hasValue) {
    return null;
  }
  return type as GoalProgressChange;
};

export const getHasValue = (
  isBinaryType: boolean,
  type: number | GoalProgressChange | null,
  value: number | string | null,
) => {
  return isBinaryType ? !isNil(type) : !isNil(value) && String(value) !== '';
};
