import { openCompatibilityModal } from "../../../features/popup/popupSlice";
import { useDispatch, useSelector } from "react-redux";
import { useState, useRef, useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import {
  startLoading,
  stopLoading,
} from "../../../features/loading/loadingSlice";
import { productApi } from "../../../apis/productApi";
import { setAreas } from "../../../features/areas/areasSlice";
import { Area } from "../../../services/product/type";
import { useNavigate } from "react-router";
import { useTranslation } from "react-i18next";
import {
  formatCurrency,
  getWithExpiry,
  setWithExpiry,
} from "../../../logic/loigicUtils";
import { get } from "http";

const HomeSearch = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [searchQuery, setSearchQuery] = useState("");
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [areasList, setAreasList] = useState<Area[]>([]);
  const areas = getWithExpiry<Area[] | []>("areas");

  useEffect(() => {
    if (!areas || areas.length === 0) getAreaMutation.mutate();
    else {
      console.log("Areas loaded from cache:", areas.length, areas);
      setAreasList(areas);
    }
  }, []);

  const getAreaMutation = useMutation({
    mutationFn: async () => {
      dispatch(startLoading({}));
      const res = await productApi.loadArea({
        isCountry: "-1",
        isPopular: "-1",
      });
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopLoading());
      console.log("Get area response data:", data);
      if (data && data.errorCode === "0") {
        console.log("Get area successful");
        // dispatch(setAreas(data.data as Area[]));
        setWithExpiry("areas", data.data);
        setAreasList(data.data as Area[]);
      } else {
        console.error("Get area failed, no token received");
      }
    },
    onError: (error: any) => {
      dispatch(stopLoading());
      console.error("Get area error:", error.response.data);
    },
  });

  const handleSelect = (area: Area) => {
    console.log("Selected area:", area);
    setIsDropdownOpen(false);
    navigate(`/product-detail/${area.id}`, {
      state: {
        ...area,
      },
    });
  };

  const handleSearch = (query: string) => {
    setSearchQuery(query);
    if (query.trim() === "") {
      // set 10 most popular areas when input is empty
      setAreasList(areas.slice(0, 10));
    } else {
      // set time 500ms to wait for user to stop typing
      const timer = setTimeout(() => {
        // logic sau khi user ngừng gõ
        const filtered = areas.filter((area: Area) =>
          area.searchArea?.toLowerCase().includes(query.toLowerCase()),
        );
        setAreasList(filtered);
      }, 500);
      return () => {
        clearTimeout(timer); // clear nếu user gõ tiếp
      };
    }
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <section className="pt-8 pb-4 px-4 relative z-40 bg-white">
      <div className="max-w-4xl mx-auto w-full relative">
        <div className="flex justify-center mb-2 md:mb-2" ref={dropdownRef}>
          <div className="w-full max-w-3xl relative group z-30">
            <input
              type="text"
              placeholder={t("chooseTo")}
              value={searchQuery}
              onChange={(e) => {
                handleSearch(e.target.value);
                setIsDropdownOpen(true);
              }}
              onFocus={() => setIsDropdownOpen(true)}
              className="w-full bg-white rounded-full py-4 md:py-6 px-10 md:px-12 text-base md:text-xl text-slate-700 shadow-sm border border-slate-100 outline-none focus:ring-4 focus:ring-red-50 transition-all placeholder:text-slate-300"
            />
            <button className="absolute right-2 md:right-3 top-2 md:top-3 bottom-2 md:bottom-3 aspect-square bg-[#EE0434] rounded-full flex items-center justify-center text-white shadow-lg shadow-red-200 hover:scale-105 transition-all">
              <svg
                className="w-5 h-5"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                  strokeWidth={2.5}
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </button>

            {/* Dropdown Menu */}
            {isDropdownOpen && (
              <div className="absolute top-full left-0 right-0 mt-3 bg-white rounded-[24px] shadow-[0_20px_60px_-15px_rgba(0,0,0,0.15)] border border-slate-100 overflow-hidden animate-in fade-in zoom-in-95 duration-200">
                <div className="max-h-[400px] overflow-y-auto custom-scrollbar p-4">
                  <h3 className="text-xs font-bold text-slate-400 uppercase tracking-widest mb-4 px-2 sticky top-0 bg-white z-10 py-2">
                    {t("mostPopular")}
                  </h3>
                  <div className="space-y-1">
                    {areasList && areasList.length > 0 ? (
                      areasList?.map((p) => (
                        <button
                          key={p.id}
                          onClick={() => handleSelect(p)}
                          className="w-full flex items-center justify-between p-3 hover:bg-slate-50 rounded-2xl transition-all group"
                        >
                          <div className="flex items-center space-x-4">
                            <div className="w-10 h-10 rounded-full border border-slate-100 overflow-hidden shadow-sm">
                              <img
                                src={`${p.iconUrl}`}
                                alt={p.areaName1}
                                className="w-full h-full object-cover scale-150"
                              />
                            </div>
                            <span className="font-bold text-slate-700 text-lg group-hover:text-[#EE0434] transition-colors">
                              {p.areaName1}
                            </span>
                          </div>
                          <div className="text-right flex items-center space-x-2">
                            <span className="text-sm text-slate-400 font-medium">
                              {t("from")}:
                            </span>
                            <span className="text-lg font-black text-[#EE0434]">
                              {formatCurrency(p.minSellPrice, p.curency)}
                            </span>
                          </div>
                        </button>
                      ))
                    ) : (
                      <div className="text-center py-8 text-slate-400 font-medium">
                        {t("noCountryMatchesFound").replace(
                          "{searchQuery}",
                          searchQuery,
                        )}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
        <div className="flex justify-center gap-2 text-sm text-slate-400 font-medium">
          <a
            className="hover:text-[#EE0434] transition-colors underline color-hover cursor-pointer text-[18px] font-medium"
            onClick={() => {
              dispatch(openCompatibilityModal());
            }}
          >
            {t("doesEsimWorkWithMyDevice")}
          </a>
          {/* ,
          <button className="hover:text-[#EE0434] transition-colors">
            Thailand
          </button>
          ,
          <button className="hover:text-[#EE0434] transition-colors">
            China
          </button> */}
        </div>
      </div>
    </section>
  );
};

export default HomeSearch;
