import React, { useEffect } from "react";
import { ViewMode, SimProduct, SelectedProduct } from "../../services/types";
import ProductCard from "../../components/ProductCard";
import { useMutation, useQuery } from "@tanstack/react-query";
import { startLoading, stopLoading } from "../../features/loading/loadingSlice";
import { useAppDispatch } from "../../hooks/useRedux";
import { productApi } from "../../apis/productApi";
import { Area } from "../../services/product/type";
import { DataCacheKey, staleTime } from "../../global/constants";
import { useLocation, useNavigate } from "react-router-dom";
import HomeSearch from "../home/components/HomeSearch";
import { useTranslation } from "react-i18next";
import { getWithExpiry } from "../../logic/loigicUtils";

interface BuySimViewProps {
  onProductSelect: (product: SelectedProduct) => void;
  onViewChange: (view: ViewMode) => void;
}

const BuySimView: React.FC<BuySimViewProps> = ({
  onProductSelect,
  onViewChange,
}) => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const location = useLocation();
  const state = location.state;
  const areas = getWithExpiry<Area[] | []>("areas");
  // const [countries, setCountries] = React.useState<Area[]>([]);
  // const [populars, setPopulars] = React.useState<Area[]>([]);

  const { data: loadArea = [] } = useQuery<Area[]>({
    queryKey: [DataCacheKey.AREAS],
    queryFn: async (): Promise<Area[]> => {
      try {
        dispatch(startLoading({}));
        const res = await productApi.loadArea({
          isCountry: "-1",
          isPopular: "-1",
        });
        // save to redux store
        console.log("Get area response data:", res);
        let areas = res.data as Area[];
        // setCountries(areas.filter((a) => a.isCountry === 1));
        // setPopulars(areas.filter((a) => a.isPopular === 0));
        return res.data as Area[];
      } catch (error) {
        console.error(error);
        return []; // 🔴 bắt buộc
      } finally {
        dispatch(stopLoading());
      }
    },
    staleTime: staleTime,
  });

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

  const handleSelect = (p: Area) => {
    // open product detail view
    navigate(`/product-detail/${p.id}`, {
      state: {
        ...p,
      },
    });
  };

  // useEffect(() => {
  //   if (!areas || areas.length === 0) getAreaMutation.mutate();
  //   else {
  //     console.log("Areas loaded from cache:", areas.length, areas);
  //     setCountries(areas.filter((a) => a.isCountry === 1));
  //     setPopulars(areas.filter((a) => a.isPopular === 0));
  //   }
  // }, []);

  useEffect(() => {
    if (!state?.scrollToId || loadArea.length === 0) return;

    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        scrollToSection();
      });
    });
  }, [loadArea, state?.scrollToId]);

  const scrollToSection = () => {
    const element = document.getElementById(state?.scrollToId);
    if (element) {
      element.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  };

  const countries = React.useMemo(
    () => loadArea.filter((a) => a.isCountry === 1),
    [loadArea],
  );

  const regions = React.useMemo(
    () => loadArea.filter((a) => a.isCountry === 0),
    [loadArea],
  );

  return (
    <div className="bg-[#fcfdfe] min-h-screen">
      <div className="max-w-7xl mx-auto px-4 py-4 md:py-6 border-b border-slate-50">
        <nav className="flex items-center space-x-2 text-xs md:text-sm text-slate-500 ">
          <button
            onClick={() => onViewChange(ViewMode.HOME)}
            className="hover:text-[#EE0434] text-[18px]"
          >
            {t("home")}
          </button>
          <svg
            className="w-3 h-3"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              d="M9 5l7 7-7 7"
              strokeWidth={2.5}
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span className="text-slate-900 font-bold text-[18px]">
            {t("buySim")}
          </span>
        </nav>
      </div>

      <div className="max-w-7xl mx-auto px-4">
        <div className="mb-12">
          <HomeSearch />
        </div>
        <section className="mb-12" id="countries">
          <h2 className="text-xl md:text-[32px] font-black text-slate-900 mb-6 md:mb-8 tracking-tight">
            {t("simCountries")}
          </h2>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-6">
            {countries.map((p) => (
              <ProductCard key={p.id} p={p} onClick={handleSelect} />
            ))}
          </div>
        </section>
        <section className="mb-12" id="regions">
          <h2 className="text-xl md:text-[32px] font-black text-slate-900 mb-6 md:mb-8 tracking-tight">
            SIM {t("regionList")}
          </h2>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-6">
            {regions.map((p) => (
              <ProductCard key={p.id} p={p} onClick={handleSelect} />
            ))}
          </div>
        </section>
      </div>
    </div>
  );
};

export default BuySimView;
