import { useState } from 'react'
import { useFormData } from '../FormContext/'
import Modal from './Modal'

export default function Verschoben({onNext, isCompleted}) {
    const { formData, updateFormData } = useFormData()
    
    // State für das selektierte Datum
    const [selectedDate, setSelectedDate] = useState(formData.neuesDatum || '')
    const [showModal, setShowModal] = useState(false)

    const handleOK = () => {
        if (selectedDate) {
            updateFormData('neuesDatum', selectedDate)
            onNext()
        } else {
            setShowModal(true)
        }
    }

    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            handleOK()
        }
    }

    const closeModal = () => {
        setShowModal(false)
    }
    
    let now = new Date()
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());

    return (
        <>
            <section>
                <h3>Verschoben auf:</h3>
                <div className="verschoben">
                        <input 
                            type="datetime-local" 
                            id="datetime" 
                            value={selectedDate}
                            onChange={(e) => {
                                let selD = e.target.value
                                selD = selD + ':00'
                                selD = selD.replace('T',' ')
                                setSelectedDate(selD)
                            }}
                            onKeyDown={handleKeyDown}
                            min={now.toISOString().slice(0,16)} 
                            disabled={isCompleted}
                        />        
                        <button className="okbutton" onClick={handleOK}>OK</button>
        
                </div>
                <p style={{ fontWeight: 'normal', fontSize: '0.9em', marginTop: '1.5em' }}>
                    Falls noch kein Termin bekannt ist, bitte <strong>31.12.2099 20:00</strong> eingeben.
                </p>
            </section>
            
            <Modal 
                isOpen={showModal} 
                onClose={closeModal}
                title="Datum erforderlich"
            >
                <p>Bitte ein Datum auswählen</p>
            </Modal>
        </>
    )
}