import { Typography } from "@mui/material";
import { useEffect, useState } from "react";
import { PropTypes } from "prop-types";
import { toHHMMSS } from "../../utils/toHHMMSS";
import { toDDHHMMSS } from "../../utils/toDDHHMMSS";
import FiberManualRecordIcon from "@mui/icons-material/FiberManualRecord";
import { Grid } from "../grid/Grid";

export const Timer = ({ seconds, isFilePaymentTime }) => {
  isFilePaymentTime = isFilePaymentTime || false;
  const [currentCount, setCount] = useState(Math.round(seconds));
  const timer = () => {
    setCount((prevState) => prevState - 1);
  };

  useEffect(() => {
    setCount(seconds);
    return () => setCount(0);
  }, [seconds]);

  useEffect(() => {
    if (currentCount <= 0) {
      return;
    }
    const id = setInterval(timer, 1000);
    return () => clearInterval(id);
  }, []);

  const auctionTimer =
    currentCount <= 0 ? "پایان یافته!" : toHHMMSS(currentCount);

  const fileTimer =
    currentCount <= 0 ? "پایان یافته!" : toDDHHMMSS(currentCount);

  return (
    <Grid container alignItems="center" justifyContent="center">
      <FiberManualRecordIcon
        color="error"
        fontSize="small"
        className="timerIcon"
      />
      <Typography variant="body2">
        {!isFilePaymentTime && auctionTimer}
        {isFilePaymentTime && fileTimer}
      </Typography>
    </Grid>
  );
};

Timer.propTypes = {
  seconds: PropTypes.any,
  isFilePaymentTime: PropTypes.any,
};
