"use client";

import { useMemo, useState } from "react";
import { ProductCard } from "@/components/ProductCard";

type Product = {
  id: string;
  slug: string;
  name: string;
  metalType: string;
  weight: string;
  purity: string;
  productType: string;
  mintBrand?: string | null;
  brandMint?: string | null;
  customerPrice?: unknown;
  totalSalePrice?: unknown;
  manualPrice?: unknown;
  isIraEligible: boolean;
  imageUrls?: string | null;
  images?: string | null;
  stockStatus?: string | null;
  inventoryStatus?: string | null;
};

const tabs = ["Best Sellers", "New Arrivals", "Gold Picks", "Silver Picks", "IRA Eligible"];

export function HomeProductTabs({ products }: { products: Product[] }) {
  const [active, setActive] = useState(tabs[0]);
  const visible = useMemo(() => {
    if (active === "Gold Picks") return products.filter((product) => product.metalType === "GOLD").slice(0, 8);
    if (active === "Silver Picks") return products.filter((product) => product.metalType === "SILVER").slice(0, 8);
    if (active === "IRA Eligible") return products.filter((product) => product.isIraEligible).slice(0, 8);
    if (active === "New Arrivals") return products.slice(0, 8);
    return [...products].sort((a, b) => Number(b.isIraEligible) - Number(a.isIraEligible)).slice(0, 8);
  }, [active, products]);

  return (
    <div>
      <div className="flex flex-wrap gap-2 border-b border-[#E2D8C5] bg-[#FFFDF7] p-2">
        {tabs.map((tab) => (
          <button
            key={tab}
            type="button"
            onClick={() => setActive(tab)}
            className={active === tab ? "rounded border border-[#B89122] bg-[#D4AF37] px-3 py-2 text-sm font-black text-[#111] shadow-sm" : "rounded border border-[#E2D8C5] bg-white px-3 py-2 text-sm font-black text-[#444] hover:border-[#D4AF37] hover:bg-[#FBF7EC]"}
          >
            {tab}
          </button>
        ))}
      </div>
      <div className="mt-5 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {visible.map((product) => <ProductCard key={product.id} product={product} />)}
      </div>
    </div>
  );
}
