import React, { useEffect, useState } from 'react';
import { Typography } from '@mui/material';

interface CountdownTimerProps {
    totalSeconds: number;
}

const CountdownTimer: React.FC<CountdownTimerProps> = ({ totalSeconds }) => {
    const [timeLeft, setTimeLeft] = useState(totalSeconds);

    useEffect(() => {
        setTimeLeft(totalSeconds); // Reset timer on prop change

        const timerId = setInterval(() => {
            setTimeLeft(prev => Math.max(prev - 1, 0));
        }, 1000);

        return () => clearInterval(timerId);
    }, [totalSeconds]); // Listen to changes in totalSeconds

    const formatTime = (seconds: number) => {
        const hrs = Math.floor(seconds / 3600);
        const min = Math.floor((seconds % 3600) / 60);
        const sec = seconds % 60;
        return `${hrs}h ${min}m ${sec}s`;
    };

    const timeColor = timeLeft < 300 ? 'red' : 'white'; // Red if less than 5 minutes remaining

    return (
        <Typography variant="body2" style={{ color: timeColor }}>
            {`Time until refill: ${formatTime(timeLeft)}`}
        </Typography>
    );
};

export default CountdownTimer;