import { useAppDispatch, useAppSelector } from "../../../hooks/useRedux";
import { SimProduct } from "@/src/services/types";
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 { setAreas } from "../../../features/areas/areasSlice";

const HomeProduct = () => {
  const [activeTab, setActiveTab] = useState<"country" | "region">("country");
  const navigate = useNavigate();

  const dispatch = useAppDispatch();

  useEffect(() => {}, []);

  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
        dispatch(setAreas(res.data as Area[]));
        return res.data as Area[];
      } catch (error) {
        console.error(error);
        return []; // 🔴 bắt buộc
      } finally {
        dispatch(stopLoading());
      }
    },
    staleTime: staleTime,
  });

  const handleProductClick = (p: Area) => {
    navigate(`/product/${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">
        Fastest Data, <span className="text-[#EE0434]">Best Prices.</span>
      </h2>
      <p className="text-slate-500 font-bold mb-10 md:mb-12">
        Connect instantly in over 200 destinations.
      </p>

      <div className="inline-flex p-1.5 bg-slate-100 rounded-full mb-12 md:mb-16 shadow-inner">
        <button
          onClick={() => setActiveTab("country")}
          className={`px-8 md:px-12 py-3 rounded-full text-xs md:text-sm 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"
          }`}
        >
          Country List
        </button>
        <button
          onClick={() => setActiveTab("region")}
          className={`px-8 md:px-12 py-3 rounded-full text-xs md:text-sm 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"
          }`}
        >
          Regions
        </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">
          {loadArea.map((p) => (
            <div
              key={p.id}
              onClick={() => handleProductClick(p)}
              className="group bg-white border border-slate-100 rounded-[32px] p-6 md:p-10 shadow-sm hover:shadow-2xl transition-all relative overflow-hidden cursor-pointer flex flex-col items-center"
            >
              <div className="absolute top-4 right-4 bg-[#EE0434] text-white text-[10px] font-black px-2.5 py-1 rounded-lg z-10">
                {p.promotionPercent}%
              </div>
              <div className="w-16 h-16 md:w-20 md:h-20 mb-6 rounded-full overflow-hidden shadow-xl border-4 border-white group-hover:scale-110 transition-transform">
                <img
                  src={`${p.iconUrl}`}
                  alt={p.areaName1}
                  className="w-full h-full object-cover scale-150"
                />
              </div>
              <h3 className="text-lg md:text-xl font-black text-slate-800 mb-2 truncate w-full group-hover:text-[#EE0434] transition-colors">
                {p.areaName1}
              </h3>
              <p className="text-xs text-slate-400 line-through mb-1">
                {p.minSellPrice} {p.curency}
              </p>
              <p className="text-lg md:text-2xl font-black text-[#EE0434]">
                From{" "}
                {p.minDisplayPrice.toLocaleString("vi-VN", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })}{" "}
                {p.curency}
              </p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

export default HomeProduct;
