import { apiUrl } from '@/Api/api';
import axios from 'axios';
import { useState } from 'react';

const CommentBoxForm = () => {
    const [formData, setFormData] = useState({
        comment: '',
        name: '',
        email: ''
    });

    const handleInputChange = (e: any) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value
        });
    };

    const handleSubmit = async (e: any) => {
        e.preventDefault();

        if (!formData.comment || !formData.name) {
            alert('Please fill in all required fields.');
            return;
        }

        try {
            const response = await axios.post(apiUrl + '/blog/comments', formData, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (response.status === 200) {
                // Reset form after successful submission
                setFormData({
                    comment: '',
                    name: '',
                    email: ''
                });
                alert('Comment posted successfully!');
            } else {
                throw new Error('Failed to post comment.');
            }
        } catch (error) {
            console.error('Error posting comment:', error);
            alert('Failed to post comment. Please try again later.');
        }
    };


    return (
        <div className="blg-dtl-boxvw mt-3">
            <h5 className="h5-tag-fntsz">Leave a Comment</h5>
            <form onSubmit={handleSubmit}>
                <textarea
                    name="comment"
                    value={formData.comment}
                    onChange={handleInputChange}
                    cols={30}
                    rows={10}
                    className="search-blg-input mt-2"
                    placeholder="Say something ..."
                    required
                ></textarea>
                <input
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    className="search-blg-input mt-2"
                    placeholder="Name*"
                    required
                />
                <input
                    type="text"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="search-blg-input mt-2"
                    placeholder="Email "

                />
                <div>
                    <button className="post-comment-btn" type="submit">Post Comment</button>
                </div>
            </form>
        </div>
    );
};

export default CommentBoxForm;
