import React, { useState } from "react";
import "./Your_Location_modal.css";
import { Button, Form, InputGroup, Modal } from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faMicrophone,
  faSearch,
  faXmark,
} from "@fortawesome/free-solid-svg-icons";
import Confirm_Location_modal from "../Confirm_Location_modal/Confirm_Location_modal";
import Light_Gray_Outline_Btn from "../../common_btn/gray_outline_btn/Light_Gray_Outline_Btn";
import { useDispatch, useSelector } from "react-redux";
import {
  getAllGooglePlaces,
  getCurrentLocation,
  setCurrentLocation,
} from "../../../../features/location/locationSlice";

function Your_Location_modal(props) {
  const [searchQuery, setSearchQuery] = useState("");
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [showConfimLocModal, setShowConfimLocModal] = useState(false);
  const [isFetchingLocation, setIsFetchingLocation] = useState(false); // State for location fetching
  const [locations] = useState([
    {
      title: "Kuwait",
      address:
        "7, Bader Mohammad Nasser Al Sayer Street, Block 3 Abdullah Al-Salem, Kuwait City, Al Asimah, 25501",
    },
    { title: "Kuwait", address: "Kuwait City, Kuwait" },
    { title: "Kuwait", address: "Kuwait City, Kuwait" },
    { title: "Kuwait", address: "Kuwait City, Kuwait" },
    { title: "Kuwait", address: "Kuwait City, Kuwait" },
    {
      title: "Kuwait",
      address:
        "7, Bader Mohammad Nasser Al Sayer Street, Block 3 Abdullah Al-Salem, Kuwait City, Al Asimah, 25501",
    },
  ]);
  const [selectedLocation, setSelectedLocation] = useState("");
  // Handle search query changes and open/close dropdown
  const handleSearchChange = (event) => {
    const query = event.target.value;
    setSearchQuery(query);

    // if (query.trim() !== "") {
    //   setIsDropdownOpen(true);
    // } else {
    //   setIsDropdownOpen(false);
    // }
  };

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

  // Handle enabling current location
  const handleEnableLocation = () => {
    setIsFetchingLocation(true);

    // Simulate fetching location with a timeout
    setTimeout(() => {
      setIsFetchingLocation(false);
      props.onHide(); // Close the modal after 3 seconds
    }, 3000);
  };

  // Filter locations based on the search query
  const filteredLocations = locations.filter(
    (location) =>
      location.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      location.address.toLowerCase().includes(searchQuery.toLowerCase()),
  );

  const handleShowLocationModal = async (location) => {
    setShowConfimLocModal(true);
    setSelectedLocation(location?.structured_formatting?.main_text);
    await dispatch(
      setCurrentLocation(location?.structured_formatting?.main_text),
    );
    props.onHide();
  };
  const [locationText, setLocationText] = useState("Use Current Location");
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState(false);
  const handleUseCurrentLocation = async () => {
    setIsFetchingLocation(true);
    setLocationText("Fetching your location...");
    setIsLoading(true);

    try {
      const res = await dispatch(getCurrentLocation());
      if (res.meta.requestStatus === "fulfilled") {
        setLocationText("Location fetched");
        // dispatch(setCurrentLocation(addressDetails));
        setTimeout(() => {
          setIsFetchingLocation(false);
          props.onHide(); // Close the modal after 3 seconds
        }, 2000);
      } else if (res.meta.requestStatus === "rejected") {
        console.log("Error:", res.payload || "Failed to fetch location");
        setLocationText("Failed to get location");
      }
    } catch (error) {
      console.error("Error in location fetch:", error);
      setLocationText("An unexpected error occurred.");
    } finally {
      setIsLoading(false);
    }
  };

  const SearchPlaces = async () => {
    // Use the current searchQuery state
    const query = searchQuery;

    if (!query.trim()) return; // avoid empty searches

    setIsLoading(true);
    try {
      const res = await dispatch(getAllGooglePlaces({ name: query }));
      setIsDropdownOpen(true);

      if (res.meta.requestStatus === "fulfilled") {
        
      } else if (res.meta.requestStatus === "rejected") {
        console.error("Failed to fetch places");
      }
    } catch (error) {
      console.error("Error in location fetch:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const google_location = useSelector(
    (state) => state.location.google_location,
  );


  return (
    <>
      <section className="Your_Location_modal">
        <Modal
          {...props}
          size="lg"
          aria-labelledby="contained-modal-title-vcenter"
          centered
          className="Your_Location_modal modal-holder"
        >
          <Modal.Header className="common_modal_header">
            <Modal.Title>Your Location</Modal.Title>
            <div className="right_side_close_modal_btn">
              <img
                src="/assets/images/location_offcanvas/close.png"
                className="close_modal_img"
                onClick={() => {
                  props?.onHide();
                }}
              />
            </div>
          </Modal.Header>

          <Modal.Body>
            <div className="search-field-holder">
              <div className="search-field">
                <InputGroup className="location_input_group mb-3">
                  <InputGroup.Text id="basic-addon1"></InputGroup.Text>
                  <Form.Control
                    placeholder="Search Locations"
                    aria-label="Search Locations"
                    aria-describedby="basic-addon1"
                    value={searchQuery}
                    onChange={handleSearchChange}
                  />
                  <InputGroup.Text
                    onClick={handleClearSearch}
                    className="clear-icon"
                  >
                    <FontAwesomeIcon icon={faSearch} onClick={SearchPlaces} />
                  </InputGroup.Text>
                  <InputGroup.Text
                    onClick={handleClearSearch}
                    className="clear-icon"
                  >
                    <FontAwesomeIcon icon={faXmark} />
                  </InputGroup.Text>
                </InputGroup>

                {/* <Mice_Btn_Holder/> */}
              </div>
              {isDropdownOpen && (
                <div className="option-list-holder scroll-bar-style">
                  {google_location && google_location?.places?.length > 0 ? (
                    google_location?.places?.map((location, index) => (
                      <div
                        className="option-holder"
                        key={index}
                        onClick={() => handleShowLocationModal(location)}
                      >
                        <div className="img-holder">
                          <img
                            className="location_icon_img"
                            src={
                              "/assets/images/location_offcanvas/location.png"
                            }
                            alt="location_icon_img"
                          />
                        </div>
                        <div className="text-holder">
                          <h4>{location.description}</h4>
                          <p>{location.description}</p>
                        </div>
                      </div>
                    ))
                  ) : (
                    <p>No locations found</p>
                  )}
                </div>
              )}
            
            </div>

            <div className="current-location-text-holder">
              <div className="address-text-holder">
                <div className="icon-holder">
                  <img
                    className="icon-img"
                    src={
                      "/assets/images/location_offcanvas/target.png"
                    }
                    alt="Current Location Icon"
                  />
                </div>
                <div className="text-holder">
                  <h6>
                    {isFetchingLocation
                      ? "Fetching your location..."
                      : "Current Location"}
                  </h6>
                  <p
                    style={{
                      color: isFetchingLocation ? "#6EC090" : "#707070",
                    }}
                  >
                    {isFetchingLocation
                      ? "Using GPS"
                      : "Enable your current location for better services"}
                  </p>
                </div>
              </div>

              {!isFetchingLocation && (
                <div className="text-center btn_holder">
                  <Light_Gray_Outline_Btn
                    className="enable_Btn"
                    type="button"
                    onClick={handleEnableLocation}
                    btnText={"Enable"}
                  />
                </div>
              )}
            </div>
          </Modal.Body>
        </Modal>

        <Confirm_Location_modal
          show={showConfimLocModal}
          onBackaction={() => {
            setShowConfimLocModal(false);
            props?.onOpen();
          }}
          onHide={() => {
            setShowConfimLocModal(false);
          }}
          modalTitle="Your Location Info"
          green_btn_text={"Confirm and Continue"}
          selectedLocation={selectedLocation}
          setSelectedLocation={setSelectedLocation}
        />
      </section>
    </>
  );
}

export default Your_Location_modal;
