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

export default function BesucherBar({ title, euro, onNext, isCompleted }) {

    const { formData, updateFormData } = useFormData()

        // Bestimme Feldname basierend auf dem title
    const fieldName = title.includes('Barspende') ? 'betrag' : 'besucher'

    const [wert, setWert] = useState(formData[fieldName] || '')
    const [showModal, setShowModal] = useState(false)

    const handleOK = () => {
        if (wert) {
            updateFormData(fieldName, wert)
            onNext()
        } else {
            setShowModal(true)
        }
    }

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

    const closeModal = () => {
        setShowModal(false)
    }

    return (
        <>
            <section id="besucherbar">
                <h3>{title}:</h3>
                <div className="besadiv">
                    <input type='number' value={wert} onChange={(e) => setWert(e.target.value)}
                        onKeyDown={handleKeyDown}
                        placeholder={euro ? 'Betrag in Euro' : 'Anzahl'} disabled={isCompleted}
                    />
                    &nbsp;&nbsp;{euro}
                    <button className="okbutton" onClick={handleOK}>OK</button>
                </div>
            </section>
            
            <Modal 
                isOpen={showModal} 
                onClose={closeModal}
                title="Eingabe erforderlich"
            >
                <p>Bitte einen Wert eingeben</p>
            </Modal>
        </>
    )
}
