import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
	FormRowGroup,
	FormLabel,
	TimeContainer,
	StyledSelectInput,
	TimeSeparator,
} from '../../../styles/ModuleComponents';
import { HourList, MinuteList } from '../../../assets/data';

const SingleTimePicker = ({
							  label,
							  selectedTime,
							  onTimeChange,
							  disabled,
							  reset = false,
						  }) => {
	const { t } = useTranslation();
	const [hour, setHour] = useState('00');
	const [minute, setMinute] = useState('00');

	useEffect(() => {
		if (selectedTime) {
			const time = new Date(selectedTime);
			setHour(String(time.getHours()).padStart(2, '0'));
			setMinute(String(time.getMinutes()).padStart(2, '0'));
		}
	}, [selectedTime]);

	useEffect(() => {
		if (reset) {
			setHour('00');
			setMinute('00');
		}
	}, [reset]);

	const handleTimeChange = (e) => {
		const { id, value } = e.target;
		const time = selectedTime ? new Date(selectedTime) : new Date();

		if (id === 'hour') {
			setHour(value);
			time.setHours(parseInt(value), parseInt(minute));
		} else {
			setMinute(value);
			time.setHours(parseInt(hour), parseInt(value));
		}

		onTimeChange(time);
	};

	return (
		<>
			{label && <FormLabel>{label}</FormLabel>}
			<TimeContainer>
				<StyledSelectInput
					onChange={handleTimeChange}
					id="hour"
					value={hour}
					disabled={disabled}
				>
					{HourList.map(h => (
						<option value={h} key={h}>{h}</option>
					))}
				</StyledSelectInput>
				<TimeSeparator>:</TimeSeparator>
				<StyledSelectInput
					onChange={handleTimeChange}
					id="min"
					value={minute}
					disabled={disabled}
				>
					{MinuteList.map(m => (
						<option value={m} key={m}>{m}</option>
					))}
				</StyledSelectInput>
			</TimeContainer>
		</>
	);
};

export default SingleTimePicker;