import { FC } from 'react';

import LinearProgress, {
  linearProgressClasses,
} from '@material-hu/mui/LinearProgress';
import Stack from '@material-hu/mui/Stack';
import { alpha, useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { useLokaliseTranslation } from 'src/utils/i18n';
import roundDecimals from 'src/utils/roundDecimals';
import {
  displayHoursAndMinutes,
  normaliseBarValue,
} from 'src/utils/timeTracking';

import { TOOLTIP_DELAY } from '../constants';

type Props = {
  worked: number;
  estimated: number;
  extra: number;
  isDayOffOrHoliday: boolean;
  autoClosed?: boolean;
  showPercentage?: boolean;
  showTooltip?: boolean;
};

const MIN_HOURS = 0;

const barSxOverrides = (color: string) => ({
  [`& .${linearProgressClasses.bar}`]: {
    backgroundColor: color,
  },
  [`& .${linearProgressClasses.determinate}`]: {
    backgroundColor: alpha(color, 0.3),
  },
});

const ProgressBar: FC<Props> = props => {
  const {
    worked,
    estimated,
    extra,
    isDayOffOrHoliday,
    showPercentage = false,
    showTooltip = false,
    autoClosed = false,
  } = props;
  const { t } = useLokaliseTranslation('time_tracker');
  const { palette } = useTheme();

  const workedButNoEstimatedHours = estimated === 0 && worked > 0;

  // extraDailyTime is when the collaborator worked on a day off or holiday
  const extraDailyTime = workedButNoEstimatedHours && isDayOffOrHoliday;
  // workedExtraHours is when the collaborator worked extra hours on a scheduled day
  const workedExtraHours = extra > 0 && !autoClosed;

  const processWorkedValues = () => {
    if (!worked && !estimated && !extra) {
      return {
        color: palette.new.border.neutral.default,
        filled: 100,
        total: 100,
      };
    }
    if (autoClosed) {
      return {
        color: palette.newBase?.yellow[500],
        filled: worked + extra,
        total: worked + extra,
      };
    }
    if (estimated || extra) {
      return {
        color: palette.new.action.button.background.primary.default,
        filled: worked,
        total: estimated + extra,
      };
    }

    return {
      color: palette.new.action.button.background.primary.default,
      filled: worked,
      total: worked,
    };
  };

  const workedHoursPercentage = roundDecimals((worked / estimated) * 100, 0);
  const barValues = processWorkedValues();

  // Limit to 100% to prevent visual issues with progress bar positioning
  const progressBarValue = Math.min(
    roundDecimals(
      normaliseBarValue(barValues.filled, MIN_HOURS, barValues.total),
      2,
    ),
    100,
  );

  return (
    <Stack
      sx={{
        alignItems: 'center',
        flexDirection: 'row',
        gap: 0.5,
      }}
    >
      {!extraDailyTime && (
        <HuTooltip
          description={
            autoClosed ? t('WORKED_TIME_AUTO_CLOSED') : t('WORKED_TIME')
          }
          disableTooltip={!showTooltip}
          direction="top"
          delay={TOOLTIP_DELAY}
        >
          <LinearProgress
            value={progressBarValue}
            variant="determinate"
            sx={{
              backgroundColor: palette.new.border.neutral.default,
              borderRadius: 0.5,
              width: `${roundDecimals(
                normaliseBarValue(barValues.total, MIN_HOURS, barValues.total),
                2,
              )}%`,
              ...(barValues.color && barSxOverrides(barValues.color)),
            }}
          />
        </HuTooltip>
      )}
      {(workedExtraHours || extraDailyTime) && (
        <HuTooltip
          description={`${t('EXTRA_TIME')}: ${displayHoursAndMinutes(
            extraDailyTime ? worked : extra,
            false,
            true,
          )}`}
          disableTooltip={!showTooltip}
          direction="top"
          delay={TOOLTIP_DELAY}
        >
          <LinearProgress
            value={100}
            variant="determinate"
            sx={{
              borderRadius: 0.5,
              width: `${roundDecimals(
                normaliseBarValue(
                  extraDailyTime ? worked : extra,
                  MIN_HOURS,
                  extraDailyTime ? worked : estimated + extra,
                ),
                2,
              )}%`,
              ...(palette.newBase?.green[700] &&
                barSxOverrides(palette.newBase?.green[700])),
            }}
          />
        </HuTooltip>
      )}

      {showPercentage && estimated > 0 && (
        <Typography
          variant="globalS"
          sx={{
            color: palette.new.text.neutral.lighter,
            whiteSpace: 'unset',
            overflow: 'visible',
            textOverflow: 'unset',
            minWidth: '5ch',
          }}
        >
          {`${workedHoursPercentage}%`}
        </Typography>
      )}
    </Stack>
  );
};

export default ProgressBar;
