"use client";

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 Image from "next/image";
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import {
  loadLocationFromStorage,
  saveLocationToStorage,
} from "../../../../utils/locationUtils";

const LocationSearchComponent = () => {
  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: RootState) => state.CurrencyReducer.selectedCurrency
  );

  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);

  // For loading location
  useEffect(() => {
    const savedLocation = loadLocationFromStorage();
    if (savedLocation) {
      dispatch(setLocation(savedLocation));
      setSelectedCountry(savedLocation.country);
      setSelectedState(savedLocation.state);
    }
  }, [dispatch]);

  // For saving location
  useEffect(() => {
    if (
      location.latitude &&
      location.longitude &&
      location.state &&
      location.country
    ) {
      saveLocationToStorage(location);
    }
  }, [location]);

  // 3. Update selected location on Redux location change
  useEffect(() => {
    if (location?.state) {
      setSelectedState(location.state);
    } else {
      setSelectedState("");
    }
  }, [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);
    setIsModalOpen(true);
  };

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

    try {
      const params = {
        page: 1,
        CurrentUserID,
        latitude,
        longitude,
        country,
        currency,
        subLocation: state,
      };

      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, state);
      setIsModalOpen(false);
      return;
    }

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

  // Add this effect to sync with Redux state
  useEffect(() => {
    if (location?.state) {
      setSelectedState(location.state);
      if (location.country) {
        setSelectedCountry(location.country);
      }
    }
  }, [location?.state, location?.country]);
  return (
    <>
      <Modal
        isOpen={isModalOpen}
        onClose={closeModal}
        title={
          loadings
            ? "..."
            : `Select a ${
                stateLocationData?.data?.type === "states"
                  ? "State"
                  : "Province"
              }`
        }
      >
        {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 cursor-pointer">
                <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 cursor-pointer"
                />
                <span className="text-black text-start cursor-pointer">
                  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 cursor-pointer"
                >
                  <input
                    type="radio"
                    name="state"
                    value={`${state.name},${state.latitude},${state.longitude}`}
                    checked={selectedState === state.name}
                    onChange={handleStateChange}
                    className="form-radio cursor-pointer"
                  />
                  <span className="text-black text-start cursor-pointer">
                    {state.name}
                  </span>
                </label>
              ))}
            </div>
          </form>
        )}

        {/* <button
          onClick={closeModal}
          className="my-6 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 items-center md:shadow-md rounded-sm px-2  "
          style={{ boxShadow: "0 0 6px 2px rgba(0.1, 0.1, 0.1, 0.1)" }}
        >
          <Image
            unoptimized
            // fill
            height={5}
            width={5}
            src={location_icon.src} // Changed for Next.js image handling
            alt="Location icon"
            className="w-5 h-5 xs:hidden md:flex"
          />

          <Menu as="div" className="relative inline-block text-left w-full">
            <Menu.Button
              className="bg-white text-black font-semibold border-none focus:outline-none text-left 
           flex xs:items-center xs:justify-center md:items-center md:justify-between xs:text-[9px] xs:w-[6rem] xs:h-[34px] xs:px-0 xs:pl-0 xs:pr-0 xs:p-0 
           md:text-sm md:pl-3 md:w-40 md:h-[44px] 
           py-2 px-2"
            >
              {selectedState
                ? `${truncateLocation(selectedState)}`
                : truncateLocation(location?.state) || "Location"}{" "}
              <ChevronDownIcon
                className="-mr-1 ml-1 xs:h-3 xs:w-3 md:h-5 md:w-5"
                aria-hidden="true"
              />
            </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-20 mt-2 md:w-44 xs:w-24 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 LocationSearchComponent;
