import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import DeliveryOrdersList from "../components/DeliveryOrdersList.jsx";
import { getTotalOrders, calculateTotalOrder } from "../api.jsx";
import { getStatuses } from "../api.jsx";
import AddOrderModal from "../components/AddOrderModal.jsx";

const Home = () => {
  const [statuses, setStatuses] = useState([]);
  const [totalOrders, setTotalOrders] = useState([]);
  const [expandedOrderId, setExpandedOrderId] = useState(null);
  const [loadingStatuses, setLoadingStatuses] = useState(true);
  const [loadingOrders, setLoadingOrders] = useState(true);
  const [loadingCreateOrder, setLoadingCreateOrder] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const navigate = useNavigate();
  const user = JSON.parse(localStorage.getItem("user"));

  useEffect(() => {
    fetchStatuses();
    fetchTotalOrders();
  }, []);

  const fetchStatuses = async () => {
    try {
      const data = await getStatuses();
      setStatuses(data);
    } catch (error) {
      if (error.response && error.response.status === 401) {
        navigate("/login");
      }
      console.error("Ошибка при загрузке статусов:", error);
    } finally {
      setLoadingStatuses(false);
    }
  };

  const fetchTotalOrders = async () => {
    try {
      const orders = await getTotalOrders();
      setTotalOrders(orders);
    } catch (error) {
      if (error.response && error.response.status === 401) {
        navigate("/login");
      }
      console.error("Ошибка при загрузке заказов:", error);
    } finally {
      setLoadingOrders(false);
    }
  };

  const handleCreateOrder = async ({ deadline, robotsCount }) => {
    setLoadingCreateOrder(true);
    try {
      await calculateTotalOrder({ deadline, robotsCount });
      alert("Начался расчет маршрутов. Заказ скоро появится в списке заказов.");
      fetchTotalOrders();
    } catch (error) {
      console.error("Ошибка при расчете заказа:", error);
    } finally {
      setLoadingCreateOrder(false);
      setShowModal(false);
    }
  };

  const handleToggleAccordion = (orderId) => {
    if (expandedOrderId === orderId) {
      setExpandedOrderId(null);
    } else {
      setExpandedOrderId(orderId);
    }
  };

  const handleSubOrderClick = (subOrderId) => {
    navigate(`/sub-orders/${subOrderId}`);
  };

  return (
    <div className="container mt-4">
      <div className="d-flex align-items-center mb-3">
        <button
          className="btn btn-primary"
          onClick={() => setShowModal(true)}
          disabled={loadingCreateOrder || loadingStatuses}
        >
          + Создать
        </button>
        {loadingCreateOrder && (
          <span className="ms-2 text-muted">
            Запрос может выполняться до 5 минут...
          </span>
        )}
      </div>

      {loadingOrders ? (
        <div className="text-center">
          <div className="spinner-border mb-2" role="status">
            <span className="visually-hidden"></span>
          </div>
        </div>
      ) : (
        totalOrders.map((order) => (
          <div key={order.id} className="card mb-2">
            <div
              className="card-header"
              onClick={() => handleToggleAccordion(order.id)}
            >
              Заказ от {new Date(order.order_datetime).toLocaleString()}
            </div>

            {expandedOrderId === order.id && (
              <div className="card-body">
                <p>
                  <strong>Статус:</strong>{" "}
                  {order.status_name || "Неизвестный статус"}
                </p>
                <p>
                  <strong>Количество роботов:</strong> {order.count_robots}
                </p>
                <p>
                  <strong>Создатель:</strong>{" "}
                  {order.user_login || "Неизвестный пользователь"}
                </p>

                <DeliveryOrdersList
                  totalOrderId={order.id}
                  onSubOrderClick={handleSubOrderClick}
                />
              </div>
            )}
          </div>
        ))
      )}

      <AddOrderModal
        show={showModal}
        onHide={() => setShowModal(false)}
        onSubmit={handleCreateOrder}
      />
    </div>
  );
};

export default Home;
