import React, { useState, useEffect } from "react";
import { MapView } from "../components/MapView";
import polyline from "@mapbox/polyline";

const Home = () => {
  const [startPoint, setStartPoint] = useState("");
  const [endPoint, setEndPoint] = useState("");
  const [startCoords, setStartCoords] = useState(null);
  const [endCoords, setEndCoords] = useState(null);
  const [route, setRoute] = useState([]);

  const handleStartChange = (e) => {
    setStartPoint(e.target.value);
  };

  const handleEndChange = (e) => {
    setEndPoint(e.target.value);
  };

  useEffect(() => {
    if (startCoords && endCoords) {
      const routeUrl = `https://router.project-osrm.org/route/v1/driving/${startCoords.lng},${startCoords.lat};${endCoords.lng},${endCoords.lat}?overview=full`;
      console.log(routeUrl);
      fetch(routeUrl)
        .then((response) => response.json())
        .then((data) => {
          if (
            data.routes &&
            data.routes.length > 0 &&
            data.routes[0].geometry
          ) {
            const geometry = data.routes[0].geometry;
            const coordinates = polyline.decode(geometry);
            setRoute(coordinates);
          } else {
            console.error("No valid routes found in response:", data);
          }
        })
        .catch((error) => {
          console.error("Error fetching route:", error);
        });
    }
  }, [startCoords, endCoords]);

  return (
    <div>
      <h1>Построить маршрут</h1>
      <input
        type="text"
        value={startPoint}
        onChange={handleStartChange}
        placeholder="Пункт отправления"
      />
      <input
        type="text"
        value={endPoint}
        onChange={handleEndChange}
        placeholder="Пункт назначения"
      />
      <button onClick={handleSearch}>Построить маршрут</button>
      <MapView startCoords={startCoords} endCoords={endCoords} route={route} />
    </div>
  );
};

export default Home;
