import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './DeliveryForm.css';

function DeliveryForm() {
  const [formData, setFormData] = useState({
    address: '',
    deliveryDate: '',
    deliveryTime: '',
    products: '',
    comment: '',
  });

  const navigate = useNavigate(); // Хук для навигации

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

  const handleSubmit = (e) => {
    e.preventDefault();
    const productsArray = formData.products.split(',').map((product) => product.trim());
    
    console.log('Order Created:', {
      ...formData,
      products: productsArray,
    });

    // Переход на страницу OrderTracking после создания заказа
    navigate('/order-tracking');
  };

  const handleBackClick = () => {
    window.history.back();
  };

  return (
    <div className="delivery-form-container">
      <h2 className='heading_h2'>Create Your Order</h2>
      <form onSubmit={handleSubmit} className="delivery-form">
        <label htmlFor="address">Delivery Address</label>
        <input
          type="text"
          id="address"
          name="address"
          value={formData.address}
          onChange={handleInputChange}
          placeholder="Enter your delivery address"
          required
        />

        <label htmlFor="deliveryDate">Delivery Date</label>
        <input
          type="date"
          id="deliveryDate"
          name="deliveryDate"
          value={formData.deliveryDate}
          onChange={handleInputChange}
          required
        />

        <label htmlFor="deliveryTime">Delivery Time</label>
        <input
          type="time"
          id="deliveryTime"
          name="deliveryTime"
          value={formData.deliveryTime}
          onChange={handleInputChange}
          required
        />

        <label htmlFor="products">Products</label>
        <input
          type="text"
          id="products"
          name="products"
          value={formData.products}
          onChange={handleInputChange}
          placeholder="Enter products (separate by comma)"
        />

        <label htmlFor="comment">Comment</label>
        <textarea
          id="comment"
          name="comment"
          value={formData.comment}
          onChange={handleInputChange}
          placeholder="Add any additional comments"
        ></textarea>

        <div className="button-group">
          <button type="submit" className="submit-button">
            Create Order
          </button>
          <button type="button" className="back-button" onClick={handleBackClick}>
            Back
          </button>
        </div>
      </form>
    </div>
  );
}

export default DeliveryForm;
