import { getDeliveryOrders } from "../api";
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

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

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

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

  const formatTimeInHours = (minutes) => {
    return (minutes / 60).toFixed(2);
  };

  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">
              <p>Подзаказ #{index + 1}</p>
              <p>
                Время на подзаказ:
                {formatTimeInHours(order.estimated_route_time_in_minutes)} час.
              </p>
            </div>
          </div>
        ))
      )}
    </div>
  );
};

export default DeliveryOrdersList;
