import React from "react";
import { useGetInventoryStatsQuery } from "../../features/report/inventoryAPI";

const StockBadge = ({ stock }) => {
  if (stock === 0) return <span className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded-full">Out of Stock</span>;
  if (stock <= 5) return <span className="px-2 py-1 text-xs bg-yellow-100 text-yellow-800 rounded-full">Low Stock</span>;
  return <span className="px-2 py-1 text-xs bg-green-100 text-green-700 rounded-full">{stock}</span>;
};

const ProductCard = ({ product }) => (
  <div className="bg-white shadow-md rounded-xl p-4 hover:shadow-xl transition transform hover:scale-105">
    <div className="flex justify-between items-center mb-2">
      <h3 className="font-semibold text-gray-800">{product.name}</h3>
      <StockBadge stock={product.stock} />
    </div>
    <p className="text-gray-500 text-sm">{product.category?.name || "Unknown Category"}</p>
  </div>
);

const InventorySection = ({ title, products }) => (
  <div className="flex flex-col gap-4">
    <h2 className="text-xl font-bold text-gray-700">{title}</h2>
    {products.length === 0 ? (
      <p className="text-gray-400 italic">No products found</p>
    ) : (
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
        {products.map((p) => (
          <ProductCard key={p._id} product={p} />
        ))}
      </div>
    )}
  </div>
);

const InventoryReport = () => {
  const { data, isLoading, isError } = useGetInventoryStatsQuery();

  if (isLoading) return <div className="text-center p-6 text-gray-500">Loading inventory...</div>;
  if (isError) return <div className="text-center p-6 text-red-500">Failed to load inventory</div>;

  const { lowStock, outOfStock, fastMoving } = data.data;

  return (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 p-6">
      <InventorySection title="Low Stock" products={lowStock} />
      <InventorySection title="Out of Stock" products={outOfStock} />
      <InventorySection title="Fast Moving" products={fastMoving} />
    </div>
  );
};

export default InventoryReport;
