import React 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 { useNavigate } from "react-router-dom";
import HomeSearch from "../home/components/HomeSearch";

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

const BuySimView: React.FC<BuySimViewProps> = ({
  onProductSelect,
  onViewChange,
}) => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  // load product by country/region or popularity

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

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

  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]"
          >
            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]">Buy Sim</span>
        </nav>
      </div>

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

export default BuySimView;
