import { Dispatch, SetStateAction } from "react";
import {
  UseFormGetValues,
  UseFormRegister,
  FieldErrors,
} from "react-hook-form";
import { Place } from "../../../data/datasource/api/entities/place";
import { Position } from "../map/map_google";
import "./assets/css/styles.css";
import axios from "axios";

// Define the props interface for the GeocodingMapbox component
interface props {
  getValues: UseFormGetValues<Place>;
  register: UseFormRegister<Place>;
  errors: FieldErrors<Place>;
  setPosition: Dispatch<SetStateAction<Position | null>>;
  setLoading: Dispatch<SetStateAction<boolean>>;
}

// GeocodingMapbox component definition
export const GeocodingMapbox = ({
  getValues,
  register,
  errors,
  setPosition,
  setLoading,
}: props) => {
  // Function to call the Mapbox API and get geocoding results
  const getResultsAPI = async (address: string) => {
    try {
      const { data } = await axios.get(
        "https://api.mapbox.com/search/geocode/v6/forward",
        {
          params: {
            q: address,
            access_token: process.env.REACT_APP_MAP_BOX || "",
          },
        }
      );
      // Set the position state with the coordinates from the API response
      setPosition({
        latitude: data.features[0].geometry.coordinates[1],
        longitude: data.features[0].geometry.coordinates[0],
      });
    } catch (error) {
      console.log("Hubo un error al obtener la direccion", error);
    }
  };

  // Function to get the position by address
  const getPositionByAddress = () => {
    const address = getValues("address");
    if (!address) return;
    setLoading(true);
    getResultsAPI(address);
    setLoading(false);
  };

  return (
    <div className="address_input_cnt">
      <label>Dirección</label>
      <div className="address_locate_cnt">
        <button type="button" onClick={getPositionByAddress}>
          {" "}
          Ubicar
        </button>
        <input
          type="text"
          {...register("address")}
          onKeyDown={(event) => {
            if (event.key === "Enter") {
              getPositionByAddress();
            }
          }}
        />
      </div>
      <p className="error">{errors.address?.message}</p>
    </div>
  );
};
