import { FC, useEffect, useState } from 'react';

import { format as formatFNS } from 'date-fns';

import Typography, { TypographyProps } from '@material-hu/mui/Typography';

import useInterval from 'src/hooks/useInterval';
import { Duration } from 'src/types/date';
import { getTotalDuration } from 'src/utils/date';

const formatTime = (milliseconds: number) => {
  const date = new Date(0);
  date.setMilliseconds(milliseconds);

  return formatFNS(date, 'mm:ss');
};

export type CountdownProps = TypographyProps & {
  duration: Duration;
  step?: number;
  format?: (milliseconds: number) => string;
  onFinish?: () => void;
};

export const Countdown: FC<CountdownProps> = props => {
  const {
    duration,
    step = 1000,
    format = formatTime,
    onFinish = () => null,
    ...typographyProps
  } = props;

  const [count, setCount] = useState(getTotalDuration(duration).milliseconds);

  useInterval((id: number) => {
    count > 0 ? setCount(Math.max(count - step, 0)) : clearInterval(id);
  }, step);

  useEffect(() => {
    if (count === 0) {
      onFinish();
    }
  }, [count]);

  return (
    <Typography
      variant="globalS"
      fontWeight="fontWeightSemiBold"
      {...typographyProps}
    >
      {format(count)}
    </Typography>
  );
};

export default Countdown;
