import React, { useState, useEffect, Fragment } from "react";
import location_icon from "../../../../assets/location_icon.svg";
import { RootState, AppDispatch } from "../../../../store";
import { useSelector, useDispatch } from "react-redux";
import { stateLocation, auctionListing } from "../../../../api/api";
import Modal from "./modal";
import { truncateLocation } from "../../../../utils/commonFunction";
import { setLocation } from "../../../../slice/LocationSlice";
import { Menu, Transition } from "@headlessui/react";
import { MdKeyboardArrowDown } from "react-icons/md";
import Image from "next/image";

const LocationSearchComponentMobile = () => {
  const dispatch = useDispatch<AppDispatch>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedCountry, setSelectedCountry] = useState<string>("");
  const [selectedState, setSelectedState] = useState<string | null>(null);
  const currency = useSelector((state: any) => state.CurrencyReducer);
  const closeModal = () => setIsModalOpen(false);
  const { stateLocationData, loadings } = useSelector(
    (state: RootState) => state.StateLocationReducer
  );
  const { userData } = useSelector((state: RootState) => state.loginReducer);
  const CurrentUserID = userData?.data?.user?.id;
  const location = useSelector((state: RootState) => state.locationReducer);

  // 1. Load from localStorage on mount
  useEffect(() => {
    const savedLocation = localStorage.getItem("location");
    if (savedLocation) {
      const parsedLocation = JSON.parse(savedLocation);
      dispatch(setLocation(parsedLocation));
      setSelectedCountry(parsedLocation.country);
      setSelectedState(parsedLocation.state);
    }
  }, [dispatch]);

  // 2. Save to localStorage when Redux location changes
  useEffect(() => {
    if (
      location.latitude &&
      location.longitude &&
      location.state &&
      location.country
    ) {
      localStorage.setItem("location", JSON.stringify(location));
    }
  }, [location]);

  // 3. Update selected location on Redux location change
  useEffect(() => {
    if (location?.state) {
      setSelectedState(location.state);
    }
  }, [location?.state]);

  // Fetch states dynamically when country changes
  useEffect(() => {
    if (selectedCountry === "US" || selectedCountry === "CAN") {
      dispatch(stateLocation(selectedCountry));
    }
  }, [selectedCountry, dispatch]);

  const handleCountryChange = (newCountry: string) => {
    setSelectedCountry(newCountry); // Update selected country
    setIsModalOpen(true); // Always open the modal on click
  };

  const handleSearch = async (
    latitude: string,
    longitude: string,
    country: string
  ) => {
    if (!latitude || !longitude) {
      // console.error("Latitude and longitude are required.");
      return;
    }

    try {
      const params = {
        page: 1,
        CurrentUserID,
        latitude,
        longitude,
        country,
        currency: currency?.selectedCurrency,
      };

      await dispatch(auctionListing(params)).unwrap();
    } catch {
      // console.error("Search failed:", err);
      return null;
    }
  };

  const handleStateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const [state, lat, long] = event.target.value.split(",");

    if (state === "All") {
      const fullState = selectedCountry === "CAN" ? "Canada" : "USA";
      setSelectedState(fullState);

      dispatch(
        setLocation({
          latitude: lat,
          longitude: long,
          state: fullState,
          country: selectedCountry,
        })
      );
      handleSearch(lat, long, selectedCountry);
      setIsModalOpen(false);
      return;
    }

    setSelectedState(state);
    dispatch(
      setLocation({
        latitude: lat,
        longitude: long,
        state,
        country: selectedCountry,
      })
    );
    handleSearch(lat, long, selectedCountry);
    setIsModalOpen(false);
  };

  return (
    <>
      <Modal isOpen={isModalOpen} onClose={closeModal} title="Select a State">
        {loadings ? (
          <p className="text-black">Loading...</p>
        ) : (
          <form>
            <div className="grid grid-cols-2 gap-4 text-black">
              {/* Add "All" option manually */}
              <label className="flex items-center space-x-2">
                <input
                  type="radio"
                  name="state"
                  value={`All,${
                    selectedCountry === "USA"
                      ? "38.7946,106.5348"
                      : "56.1304,106.3468"
                  }`}
                  checked={
                    selectedCountry === "CAN"
                      ? selectedState === "Canada"
                      : selectedState === "USA"
                  }
                  onChange={handleStateChange}
                  className="form-radio"
                />
                <span className="text-black text-start">
                  All of {selectedCountry === "CAN" ? "Canada" : "USA"}
                </span>
              </label>

              {stateLocationData?.data?.list.map((state: any) => (
                <label key={state.code} className="flex items-center space-x-2">
                  <input
                    type="radio"
                    name="state"
                    value={`${state.name},${state.latitude},${state.longitude}`}
                    checked={selectedState === state.name}
                    onChange={handleStateChange}
                    className="form-radio"
                  />
                  <span className="text-black text-start">{state.name}</span>
                </label>
              ))}
            </div>
          </form>
        )}

        {/* <button
          onClick={closeModal}
          className="mt-4 px-4 py-1 bg-yellow-500 cursor-pointer text-black rounded "
        >
          Close Modal
        </button> */}
      </Modal>

      {/* Dropdown menu for location */}
      <div className="flex flex-col ">
        <div className="flex gap-4 items-center md:shadow-md rounded-sm">
          <Image
            unoptimized
            src={location_icon}
            alt="Location icon"
            className="w-5 h-5 flex"
          />

          <Menu as="div" className="relative inline-block text-left w-full ">
            <Menu.Button className="bg-white flex w-full justify-between  text-black font-medium px-2 focus:outline-none border-none  md:pl-3 text-lg xs:pl-0 xs:pr-0  text-left py-0">
              {selectedState
                ? `${truncateLocation(selectedState)}`
                : truncateLocation(location?.state) || "Location"}
              <MdKeyboardArrowDown className="h-7 w-7" />
            </Menu.Button>

            <Transition
              as={Fragment}
              enter="transition ease-out duration-100"
              enterFrom="transform opacity-0 scale-95"
              enterTo="transform opacity-100 scale-100"
              leave="transition ease-in duration-75"
              leaveFrom="transform opacity-100 scale-100"
              leaveTo="transform opacity-0 scale-95"
            >
              <Menu.Items className="absolute right-1 z-10 mt-2 w-full origin-top-right divide-y divide-gray-200 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none font-semibold overflow-hidden">
                <Menu.Item>
                  {({ active }) => (
                    <div
                      className={`${
                        active || selectedCountry === "US"
                          ? "bg-navy text-white"
                          : "text-gray-900"
                      } px-4 py-2 text-sm cursor-pointer`}
                      onClick={() => handleCountryChange("US")}
                    >
                      USA
                    </div>
                  )}
                </Menu.Item>

                <Menu.Item>
                  {({ active }) => (
                    <div
                      className={`${
                        active || selectedCountry === "CAN"
                          ? "bg-navy text-white "
                          : "text-gray-900"
                      } px-4 py-2 text-sm cursor-pointer `}
                      onClick={() => handleCountryChange("CAN")}
                    >
                      Canada
                    </div>
                  )}
                </Menu.Item>
              </Menu.Items>
            </Transition>
          </Menu>
        </div>
      </div>
    </>
  );
};

export default LocationSearchComponentMobile;
