import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { addOrder } from '../mockData'; // импорт функции добавления заказа
import './DeliveryForm.css';

function DeliveryTimeForm({ title, value, onChange }) {
  return (
    <div className="delivery-form-group">
      <label htmlFor="deliveryTime">{title}</label>
      <select
        id="deliveryTime"
        name="deliveryTime"
        value={value}
        onChange={onChange}
        required
      >
        <option value="" disabled>
          Choose your desired delivery time slot
        </option>
        <option value="8:00 AM - 12:00 PM">8:00 AM - 12:00 PM</option>
        <option value="12:00 PM - 4:00 PM">12:00 PM - 4:00 PM</option>
        <option value="4:00 PM - 8:00 PM">4:00 PM - 8:00 PM</option>
      </select>
    </div>
  );
}

function DeliveryForm({ currentUserId }) {
  const navigate = useNavigate();
  const location = useLocation();

  const queryParams = new URLSearchParams(location.search);
  const initialAddress = queryParams.get('address') || '';
  const initialDeliveryDate = queryParams.get('deliveryDate') || '';
  const initialDeliveryTime = queryParams.get('deliveryTime') || '';

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

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

  const handleSubmit = (e) => {
    e.preventDefault();

    const productsArray = formData.products
      ? formData.products.split(',').map((product) => product.trim())
      : [];

    const newOrder = {
      userId: currentUserId, // связываем заказ с пользователем
      address: formData.address,
      deliveryDate: formData.deliveryDate,
      deliveryTime: formData.deliveryTime,
      products: productsArray,
      comment: formData.comment,
      status: 'Создан',
      orderDate: new Date().toISOString().split('T')[0],
      id: null, // будет присвоено в addOrder
    };

    addOrder(newOrder);

    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
        />

        <DeliveryTimeForm
          title="Delivery Time"
          value={formData.deliveryTime}
          onChange={handleInputChange}
        />

        <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;
