import { useEffect, useState } from 'react'
import { Number } from './Number'
import { Word } from './Word'

const days = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']

export const Clock = ({ h24 = true }) => {
	const [hour, setHour] = useState(0)
	const [minute, setMinute] = useState(0)
	const [second, setSecond] = useState(0)
	const [day, setDay] = useState(0)
	const [pm, setPm] = useState(false)

	useEffect(() => {
		const update = () => {
			const date = new Date()
			let hour = date.getHours()
			if (!h24) {
				hour = hour % 12 || 12
			}
			setHour(hour)
			setMinute(date.getMinutes())
			setSecond(date.getSeconds())
			setDay(date.getDay())
			setPm(date.getHours() >= 12)
		}

		update()

		const interval = setInterval(() => {
			update()
		}, 1000)

		return () => clearInterval(interval)
	}, [h24])

	return (
		<div className='clock shadow border m-2 rounded-lg flex items-center flex-col overflow-hidden px-4 py-7'>
			<div className='calendar flex gap-4 2xl:text-3xl text-xl mb-3'>
				{days.map((value, index) => (
					<Word key={value} value={value} hidden={index != day} />
				))}
			</div>
			<div className='clock-row flex gap-4 items-center'>
				<div className='hour 2xl:text-7xl text-5xl'>
					<Number value={hour} />
					<Word value={':'} />
					<Number value={minute} />
					<Word value={':'} />
					<Number value={second} />
				</div>
				<div className='ampm 2xl:text-5xl text-4xl'>
					<Word value={'AM'} hidden={pm} />
					<Word value={'PM'} hidden={!pm} />
				</div>
			</div>
		</div>
	)
}
