import React, { useState } from 'react';

function ContactForm() {
    const [state, setState] = useState({
        name: '',
        email: '',
        message: ''
    });

    const handleChange = (e) => {
        const { name, value } = e.target;
        setState(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        // Replace YOUR_FORM_ID with the actual ID provided by Formspree
        const formAction = 'https://formspree.io/f/YOUR_FORM_ID';
        fetch(formAction, {
            method: 'POST',
            body: JSON.stringify(state),
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
        })
        .then(response => {
            if (response.ok) {
                alert('Message sent successfully.');
                setState({
                    name: '',
                    email: '',
                    message: ''
                });
            } else {
                alert('There was a problem with your submission. Please try again.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please try again later.');
        });
    };

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="name">Name:</label>
            <input
                type="text"
                id="name"
                name="name"
                value={state.name}
                onChange={handleChange}
                required
            />

            <label htmlFor="email">Email:</label>
            <input
                type="email"
                id="email"
                name="email"
                value={state.email}
                onChange={handleChange}
                required
            />

            <label htmlFor="message">Message:</label>
            <textarea
                id="message"
                name="message"
                value={state.message}
                onChange={handleChange}
                required
            ></textarea>

            <button type="submit">Send</button>
        </form>
    );
}

export default ContactForm;