import { getDeliveryOrders } from "../api";
import React, { useState, useEffect } from "react";

const DeliveryOrdersList = ({
  totalOrderId,
  onSubOrderClick,
  setDeliveryOrdersCount,
}) => {
  const [deliveryOrders, setDeliveryOrders] = useState([]);
  const [loadingDeliveryOrders, setLoadingDeliveryOrders] = useState(true);

  useEffect(() => {
    fetchDeliveryOrders();
  }, [totalOrderId]);

  const fetchDeliveryOrders = async () => {
    try {
      const orders = await getDeliveryOrders(totalOrderId);
      setDeliveryOrdersCount(orders.length);
      setDeliveryOrders(orders);
    } catch (error) {
      console.error("Ошибка при загрузке подзаказов:", error);
    } finally {
      setLoadingDeliveryOrders(false);
    }
  };

  return (
    <div>
      {loadingDeliveryOrders ? (
        <div className="spinner-border" role="status">
          <span className="visually-hidden"></span>
        </div>
      ) : (
        deliveryOrders.map((order, index) => (
          <div
            key={order.id}
            className="card mb-1"
            onClick={() => onSubOrderClick(order.id)}
          >
            <div className="card-body">Подзаказ #{index + 1}</div>
          </div>
        ))
      )}
    </div>
  );
};

export default DeliveryOrdersList;
