import React, { useEffect, useRef, useState } from "react";
import "./Confirm_Location_modal.css";
import { Button, InputGroup, Modal } from "react-bootstrap";

import Form from "react-bootstrap/Form";
import Back_arrow_holder from "../../Back_arrow_holder/Back_arrow_holder";

import { useDispatch } from "react-redux";
import {
  getCurrentLocation,
  setCurrentLocation,
} from "../../../../features/location/locationSlice";
import axios from "axios";
import Cookies from "js-cookie";
import { faSearch, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Green_btn from "../../common_btn/green_btn/Green_btn";
import { useRouter } from "next/navigation";
function Confirm_Location_modal({
  selectedLocation,
  setSelectedLocation,
  ...props
}) {
  const navigate = useRouter();

  const handleOrangeButtonClick = () => {
    props.onHide(); // Close the modal
    navigate.push("/add-new-address"); // Redirect to /add-new-address
  };

  const [searchQuery, setSearchQuery] = useState("");
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [locations, setLocations] = useState([]); // Store filtered locations here
  const [isFetchingLocation, setIsFetchingLocation] = useState(false); // For displaying fetching status
  const dispatch = useDispatch();
  const [micOn, setMicOn] = useState(false);
  const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY;
  // Handle search query changes and open/close dropdown
  const handleSearchChange = (query) => {
    if (query.trim() !== "") {
      setIsDropdownOpen(true);
      fetchLocationByQuery(query);
    } else {
      setIsDropdownOpen(false);
    }
  };

  useEffect(() => {
    handleSearchChange(searchQuery);
  }, [searchQuery]);
  useEffect(() => {
    setSearchQuery(selectedLocation);
  }, [selectedLocation]);

  const fetchLocationByQuery = async (query) => {
    setIsFetchingLocation(true);
    try {
      const response = await fetch(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${query}&key=${apiKey}`,
      );
      const data = await response.json();
      setLocations(data);
      setIsFetchingLocation(false);

      if (data.results.length > 0) {
        const coords = {
          lat: data.results[0].geometry.location.lat,
          lng: data.results[0].geometry.location.lng,
        };

        // Center map and place marker
        const map = new window.google.maps.Map(mapRef.current, {
          center: coords,
          zoom: 15,
        });

        new window.google.maps.Marker({
          position: coords,
          map: map,
          title: "Searched Location",
          icon: {
            url: "assets/images/location/pin-point.png",
            scaledSize: new window.google.maps.Size(40, 40),
            anchor: new window.google.maps.Point(20, 40),
          },
        });

        // Reverse geocode for full address
        reverseGeocode(coords.lat, coords.lng);

        // Save last coordinates
        Cookies.set("last_coords", JSON.stringify(coords));
      }
    } catch (error) {
      console.error("Error fetching location:", error);
      setIsFetchingLocation(false);
    }
  };

  // Handle the clear icon click event and clear the search field
  const handleClearSearch = () => {
    setSearchQuery("");
    setIsDropdownOpen(false);
  };

  const onEnableAutoFacth = async () => {
    await dispatch(getCurrentLocation());
    props.onHide();
  };

  const [address, setAddress] = useState(null); // Store address details
  const mapRef = useRef(null);

  useEffect(() => {
    // Ensure Google Maps API is loaded
    const script = document.createElement("script");
    script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=initMap`;
    script.async = true;
    script.defer = true;
    window.initMap = initMap;
    document.head.appendChild(script);

    // Cleanup the script on component unmount
    return () => {
      document.head.removeChild(script);
    };
  }, [props.show]);

  // Initialize the Google Map
  const initMap = () => {
    const lastCoords = Cookies.get("last_coords");
    const defaultCoords = { lat: 18.51222785666292, lng: 73.87566681741158 };
    const coords = lastCoords ? JSON.parse(lastCoords) : defaultCoords;

    const map = new window.google.maps.Map(mapRef.current, {
      center: coords,
      zoom: 14,
    });

    let marker = null;

    // Place marker if last clicked coords exist
    if (lastCoords) {
      marker = new window.google.maps.Marker({
        position: coords,
        map: map,
        title: "Last Selected Location",
        icon: {
          url: "assets/images/location/pin-point.png",
          scaledSize: new window.google.maps.Size(40, 40),
          anchor: new window.google.maps.Point(20, 40),
        },
      });
    }

    map.addListener("click", (event) => {
      const clickedLocation = event.latLng;
      const lat = clickedLocation.lat();
      const lng = clickedLocation.lng();

      if (!marker) {
        marker = new window.google.maps.Marker({
          position: clickedLocation,
          map: map,
          icon: {
            url: "assets/images/location/pin-point.png",
            scaledSize: new window.google.maps.Size(40, 40),
            anchor: new window.google.maps.Point(20, 40),
          },
        });
      } else {
        marker.setPosition(clickedLocation);
      }

      reverseGeocode(lat, lng);
      Cookies.set("last_coords", JSON.stringify({ lat, lng })); // Save the new location
    });
  };

  // Reverse geocoding function to get full address
  const reverseGeocode = async (lat, lng) => {
    try {
      // Replace with your Google Maps API key
      const response = await axios.get(
        `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${apiKey}`,
      );

      if (response.data.status === "OK") {
        const addressDetails = response.data.results[0];
        await setAddress(addressDetails);
        Cookies.set(
          "current_location_gurukrupa",
          JSON.stringify(addressDetails),
        );
        dispatch(setCurrentLocation(addressDetails));
      } else {
        console.error("Error fetching address:", response.data.status);
      }
    } catch (error) {
      console.error("Geocoding API error:", error);
    }
  };

  return (
    <>
      <section className="Confirm_Location_modal modal-holder">
        <Modal
          {...props}
          size="lg"
          aria-labelledby="contained-modal-title-vcenter"
          centered
          className="Confirm_Location_modal modal-holder"
        >
          <Modal.Header>
            <Back_arrow_holder onClick={() => props.onBackaction()} />
            <Modal.Title>Confirm Location</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div className="search-field-holder">
              <div className="search-field p-2">
                <InputGroup className="mb-3">
                  <Form.Control
                    placeholder="Search Locations"
                    aria-label="Search Locations"
                    aria-describedby="basic-addon1"
                    value={searchQuery}
                    onChange={(event) => setSearchQuery(event.target.value)}
                  />
                  <InputGroup.Text id="basic-addon1">
                    <FontAwesomeIcon icon={faSearch} />
                  </InputGroup.Text>

                  <InputGroup.Text
                    onClick={handleClearSearch}
                    className="clear-icon"
                  >
                    <FontAwesomeIcon icon={faXmark} />
                  </InputGroup.Text>
                </InputGroup>

                {/* <Mice_Btn_Holder /> */}
              </div>
            </div>
            <div
              id="map"
              ref={mapRef}
              style={{ width: "100%", height: "500px" }}
            ></div>
          </Modal.Body>
          <div className="footer-btn-holder">
            <p className="town_text">
              {address?.address_components[1]?.long_name}
            </p>
            <p className="full_address">{address?.formatted_address}</p>

            <div className="text-center btn_holder">
              <Green_btn
                btnText={props?.green_btn_text}
                onClick={() => props.onHide()}
              />
            </div>
          </div>
        </Modal>
      </section>
    </>
  );
}

export default Confirm_Location_modal;
