import logo from './logo.svg';
import './App.css';
import React, { useEffect, useState } from 'react';

// TimerControl
const TimerControl = () => {
    const [hours, setHours] = useState('')
    const [minutes, setMinutes] = useState('')
    const [seconds, setSeconds] = useState('')
    const [count, setCount] = useState()
    const [isRunning, setIsRunning] = useState(false)

    // переводим время в секунды
    const ms = +hours * 60 * 60 + +minutes * 60 + +seconds

    useEffect(() => setCount(ms), [ms])

    // функция-перевод секунд в нормальный вид
    function timerFormat(time) {
        const h = Math.floor(time / 60 / 60)
        const m = Math.floor(time / 60) - (h * 60)
        const s = time % 60

        const defaultZero = (param) => (param > 9) ? param : '0' + param

        return `${defaultZero(h)} : ${defaultZero(m)} : ${defaultZero(s)}`
    }

    // таймер
    useEffect(() => {
        if (isRunning) {
            const int = setInterval(() => {
                setCount(count => {
                    if (count <= 0) {
                        setIsRunning(false)
                        return 0
                    }
                    return count - 1
                })
            }, 1000)
            return () => clearInterval(int)
        }
    }, [isRunning])

    return (
        <div>
            <h2>TimerControl</h2>
            {timerFormat(count)}
            <br />
            <input type='number' min='0' max='23' placeholder='00' onChange={e => setHours(e.target.value)}></input>
            <input type='number' min='0' max='59' placeholder='00' onChange={e => setMinutes(e.target.value)}></input>
            <input type='number' min='0' max='59' placeholder='00' onChange={e => setSeconds(e.target.value)}></input>
            <br />
            <button onClick={() => { setIsRunning(!isRunning) }}>{isRunning ? 'Pause' : 'Start'}</button>
        </div >
    )
}

function App() {
    return (
        <div className="App">
            <header>

                {/* TimerControl */}
                <TimerControl />

            </header>
        </div>
    );
}

export default App;