import { useState, useEffect, useRef } from 'react';
import styles from './styles.module.scss';

const CountDown = ({ times, onEnd }) => {
    const [hour, setHour] = useState("");
    const [minute, setMinute] = useState("");
    const [seconds, setSeconds] = useState("");
    const [leftTimes, setLeftTimes] = useState(times);
    const timer = useRef(null);

    useEffect(() => {
        if (timer.current != null) {
            clearTimeout(timer.current);
        }
    }, [])
    useEffect(() => {
        let s = Math.max(0, Math.floor(leftTimes));
        setHour(String(Math.floor(s / 3600)).padStart(2, '0'));
        setMinute(String(Math.floor((s % 3600) / 60)).padStart(2, '0'));
        setSeconds(String(s % 60).padStart(2, '0'));

        if (leftTimes === 0) {
            onEnd && onEnd();
            return;
        }

        timer.current = setTimeout(() => {
            setLeftTimes(leftTimes - 1);
        }, 1000);
    }, [leftTimes])
    return (
        <div className={styles.container}>
            <div className={styles.times_item}>{hour}</div>:
            <div className={styles.times_item}>{minute}</div>:
            <div className={styles.times_item}>{seconds}</div>
        </div>
    )
}

export default CountDown;