import { useAppDispatch, useAppSelector } from "../../../hooks/useRedux";
import { useMutation, useQuery } from "@tanstack/react-query";
import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { productApi } from "../../../apis/productApi";
import {
  startLoading,
  stopLoading,
} from "../../../features/loading/loadingSlice";
import { DataCacheKey, staleTime } from "../../../global/constants";
import { Area } from "../../../services/product/type";
import { formatCurrency, formatNumber } from "../../../logic/loigicUtils";
import { useTranslation } from "react-i18next";
import ProductCard from "../../../components/ProductCard";

const HomeProduct = () => {
  const [activeTab, setActiveTab] = useState<"country" | "region">("country");
  const navigate = useNavigate();
  const [areasList, setAreasList] = useState<Area[]>([]);
  const { t } = useTranslation();
  const dispatch = useAppDispatch();

  useEffect(() => {
    getAreaMutation.mutate();
  }, []);

  const getAreaMutation = useMutation({
    mutationFn: async () => {
      dispatch(startLoading({}));
      const res = await productApi.loadArea(
        activeTab === "country"
          ? {
              isCountry: "1",
              isPopular: "1",
            }
          : {
              isCountry: "0",
              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");
        const areas = data.data as Area[];
        setAreasList(areas.slice(0, 8));
      } else {
        console.error("Get area failed, no token received");
      }
    },
    onError: (error: any) => {
      dispatch(stopLoading());
      console.error("Get area error:", error.response.data);
    },
  });

  const handleProductClick = (p: Area) => {
    navigate(`/product-detail/${p.id}`, {
      state: {
        ...p,
      },
    });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  return (
    <section className="pt-12 pb-20 text-center px-4">
      <h2 className="text-3xl md:text-5xl lg:text-6xl font-black text-slate-900 tracking-tight mb-4">
        {t("fastestData")},{" "}
        <span className="text-[#EE0434]">{t("bestPrices")}</span>
      </h2>
      <p className="text-slate-500 font-bold mb-10 md:mb-12">
        {t("connectInstantlyInOver200Destinations")}
      </p>

      <div className="inline-flex p-1.5 bg-slate-100 rounded-full mb-12 md:mb-16 shadow-inner">
        <button
          onClick={() => {
            setActiveTab("country");
            getAreaMutation.mutate();
          }}
          className={`px-8 md:px-12 py-3 rounded-full text-lg md:text-xs lg:text-xl font-black transition-all ${
            activeTab === "country"
              ? "bg-gradient-to-r from-[#E21c34] to-[#500B28] text-white shadow-lg"
              : "bg-[#f0f0f0] text-[#8b8e96] hover:text-slate-800"
          }`}
        >
          {t("countryList")}
        </button>
        <button
          onClick={() => {
            setActiveTab("region");
            getAreaMutation.mutate();
          }}
          className={`px-8 md:px-12 py-3 rounded-full text-lg md:text-xs lg:text-xl  font-black transition-all ${
            activeTab === "region"
              ? "bg-gradient-to-r from-[#E21c34] to-[#500B28] text-white shadow-lg"
              : "bg-[#f0f0f0] text-[#8b8e96] hover:text-slate-800"
          }`}
        >
          {t("regionList")}
        </button>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-8">
          {areasList.map((p) => (
            <ProductCard key={p.id} p={p} onClick={handleProductClick} />
          ))}
        </div>
      </div>
      <div className="max-w-7xl mx-auto flex flex-col items-center mt-16">
        <button
          className="flex items-center bg-gradient-to-r from-[#E21c34] to-[#500B28] p-2 pr-10 rounded-full shadow-xl hover:scale-105 transition-all"
          onClick={() =>
            navigate("/buy-sim", {
              state: {
                scrollToId: activeTab === "country" ? "countries" : "regions",
              },
            })
          }
        >
          <div className="w-16 h-16 bg-white rounded-full flex items-center justify-center text-slate-800">
            <svg
              className="w-8 h-8"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2.5}
                d="M17 8l4 4m0 0l-4 4m4-4H3"
              />
            </svg>
          </div>
          <span className="ml-6 text-white text-lg font-black">
            {t("seeMore")}
          </span>
        </button>
      </div>
    </section>
  );
};

export default HomeProduct;
