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";

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

      <div className="max-w-7xl mx-auto px-4 py-8 md:py-12">
        <div className="flex justify-center mb-12 md:mb-20">
          <div className="w-full max-w-3xl relative group">
            <input
              type="text"
              placeholder="Choose country you're going to"
              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>
          </div>
        </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;
