import React, { useState, useEffect } from "react";
import { getDeliveryAccessories, getDeliveryOrderDetails } from "../api.jsx";
import { useParams } from "react-router-dom";
import { getCoordinates } from "../geocoder.jsx";
import { useNavigate } from "react-router-dom";
import {
  MapContainer,
  TileLayer,
  Marker,
  Popup,
  Polyline,
} from "react-leaflet";
import { DivIcon } from "leaflet";
import polyline from "@mapbox/polyline";
import "./DeliveryOrderDetails.css";

const DELIVERY_CITY = {
  name: "Челябинск",
  latitude: 55.159902,
  longitude: 61.402554,
};

const DeliveryOrderDetails = () => {
  const { id: deliveryOrderId } = useParams();
  const [deliveryAccessories, setDeliveryAccessories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [coordinates, setCoordinates] = useState([]);
  const [route, setRoute] = useState([]);
  const [totalCost, setTotalCost] = useState(0);
  const [truckCount, setTruckCount] = useState(0);
  const [truckName, settruckName] = useState("");
  const navigate = useNavigate();

  useEffect(() => {
    fetchDeliveryAccessories();
  }, [deliveryOrderId]);

  const fetchDeliveryAccessories = async () => {
    try {
      const deliveryOrderDetails = await getDeliveryOrderDetails(
        deliveryOrderId
      );
      setTotalCost(deliveryOrderDetails.price);
      setTruckCount(deliveryOrderDetails.count_trucks);
      settruckName(deliveryOrderDetails.truck_name);

      const accessories = await getDeliveryAccessories(deliveryOrderId);
      setDeliveryAccessories(accessories);

      const coords = await Promise.all(
        accessories.map(async (accessory) => {
          if (accessory.latitude && accessory.longitude) {
            return {
              city: accessory.city_name,
              latitude: accessory.latitude,
              longitude: accessory.longitude,
            };
          } else {
            const coords = await getCoordinates(accessory.city_name);
            return { city: accessory.city_name, ...coords };
          }
        })
      );
      setCoordinates(coords);

      const fullCoordinates = [...coords, DELIVERY_CITY];

      if (fullCoordinates.length > 1) {
        const waypoints = fullCoordinates
          .map(({ longitude, latitude }) => `${longitude},${latitude}`)
          .join(";");
        const routeUrl = `https://router.project-osrm.org/route/v1/driving/${waypoints}?overview=full`;

        const response = await fetch(routeUrl);
        const data = await response.json();

        if (data.routes && data.routes.length > 0) {
          const geometry = data.routes[0].geometry;
          const decodedRoute = polyline.decode(geometry);
          setRoute(decodedRoute);
        }
      }
    } catch (error) {
      if (error.response && error.response.status === 401) {
        navigate("/login");
      }
      console.error("Ошибка при загрузке доставок:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="delivery-order-details">
      {loading ? (
        <div className="spinner-border" role="status">
          <span className="visually-hidden">Загрузка...</span>
        </div>
      ) : (
        <div className="content-container">
          <h2>Общая стоимость подзаказа: {totalCost} руб.</h2>
          <h3>Тип машины: {truckName}</h3>
          <h3>Количество машин: {truckCount}</h3>
          <ol className="city-list">
            {deliveryAccessories.map((accessory, index) => {
              const coord = coordinates.find(
                (c) => c.city === accessory.city_name
              );
              return (
                <li key={accessory.id} className="city-item">
                  <strong>Доставка:</strong> {accessory.accessory_name}
                  <span className="city-info">
                    (Город: {accessory.city_name}, Координаты:{" "}
                    {coord
                      ? `${coord.latitude}, ${coord.longitude}`
                      : "Не найдены"}
                    )
                  </span>
                </li>
              );
            })}
            <li className="city-item">
              <strong>Конечный пункт:</strong> {DELIVERY_CITY.name}
              <span className="city-info">
                (Координаты: {DELIVERY_CITY.latitude}, {DELIVERY_CITY.longitude}
                )
              </span>
            </li>
          </ol>
          {coordinates.length > 0 && (
            <div className="map-container">
              <MapContainer
                center={[coordinates[0].latitude, coordinates[0].longitude]}
                zoom={5}
                style={{ height: "400px", width: "100%" }}
              >
                <TileLayer
                  url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                  attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                />
                {coordinates.map((coord, index) => (
                  <Marker
                    key={index}
                    position={[coord.latitude, coord.longitude]}
                    icon={
                      new DivIcon({
                        className: "custom-marker",
                        html: `<div class='marker-number'>${index + 1}</div>`,
                        iconSize: [30, 30],
                      })
                    }
                  >
                    <Popup>{coord.city}</Popup>
                  </Marker>
                ))}
                <Marker
                  position={[DELIVERY_CITY.latitude, DELIVERY_CITY.longitude]}
                  icon={
                    new DivIcon({
                      className: "custom-marker",
                      html: `<div class='marker-number'>${
                        deliveryAccessories.length + 1
                      }</div>`,
                      iconSize: [30, 30],
                    })
                  }
                >
                  <Popup>{DELIVERY_CITY.name}</Popup>
                </Marker>
                {route.length > 0 && (
                  <Polyline positions={route} color="blue" />
                )}
              </MapContainer>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default DeliveryOrderDetails;
