// // import React from "react";
// // import { useGetProductsQuery } from "../../features/products/productApi";
// // import { Link } from "react-router-dom";
// // import { FiEye, FiEdit, FiTrash } from "react-icons/fi";

// // const ProductList = () => {
// //   const { data, isLoading, isError } = useGetProductsQuery({
// //     page: 1,
// //     limit: 10,
// //   });

// //   const handleDelete = (id) => {
// //   if (confirm("Are you sure you want to delete this product?")) {
// //     console.log("Delete Product:", id);
// //     // Later you will add RTK mutation here
// //   }
// // };

// //   const products = data?.data?.products || [];

// //   if (isLoading)
// //     return (
// //       <div className="text-center mt-10 text-gray-500">Loading products...</div>
// //     );

// //   if (isError)
// //     return (
// //       <div className="text-center mt-10 text-red-600">
// //         Failed to load products.
// //       </div>
// //     );

// //   return (
// //     <div className="space-y-6">
// //       {/* <h2 className="text-xl font-semibold text-gray-600">Products</h2> */}
// //       <div className="flex items-center justify-between mb-6">
// //         {/* LEFT SIDE TITLE */}
// //         <h2 className="text-xl font-semibold text-gray-700">Products</h2>

// //         {/* RIGHT SIDE SEARCH BAR */}
// //         <div className="flex items-center gap-3">
// //           <input
// //             type="text"
// //             placeholder="Search products..."
// //             className="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none w-60"
// //           />

// //           <Link
// //             to="/products/add"
// //             className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition"
// //           >
// //             + Add Product
// //           </Link>
// //         </div>
// //       </div>

// //       {products.length === 0 ? (
// //         <div className="text-center text-gray-500 py-10">
// //           No products found.
// //         </div>
// //       ) : (
// //         <div className="overflow-x-auto">
// //           <table className="min-w-full bg-white rounded-xl shadow-md divide-y divide-gray-200">
// //             <thead className="bg-gray-50">
// //               <tr>
// //                 <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
// //                   Sr. No
// //                 </th>
// //                 <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
// //                   Name
// //                 </th>
// //                 <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
// //                   Price
// //                 </th>
// //                 <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
// //                   Status
// //                 </th>
// //                 <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
// //                   Views
// //                 </th>
// //                 <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
// //                   Created At
// //                 </th>
// //                 <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
// //                   Actions
// //                 </th>
// //               </tr>
// //             </thead>
// //             <tbody className="divide-y divide-gray-200">
// //               {products.map((product, index) => (
// //                 <tr
// //                   key={product._id}
// //                   className="hover:bg-gray-50 transition-colors duration-150"
// //                 >
// //                   <td className="px-4 py-2 text-sm text-gray-700">
// //                     {index + 1}
// //                   </td>
// //                   <td className="px-4 py-2 text-sm text-gray-800 font-medium">
// //                     {product.name}
// //                   </td>
// //                   <td className="px-4 py-2 text-sm text-gray-700">
// //                     ₹{product.basePrice}
// //                   </td>
// //                   <td className="px-4 py-2">
// //                     <span
// //                       className={`px-2 py-1 text-xs font-semibold rounded-full ${
// //                         product.status === "active"
// //                           ? "bg-green-100 text-green-800"
// //                           : "bg-red-100 text-red-800"
// //                       }`}
// //                     >
// //                       {product.status}
// //                     </span>
// //                   </td>
// //                   <td className="px-4 py-2 text-sm text-gray-700">
// //                     {product.viewCount}
// //                   </td>
// //                   <td className="px-4 py-2 text-sm text-gray-500">
// //                     {new Date(product.createdAt).toLocaleDateString()}
// //                   </td>
// //                   {/* <td className="px-6 py-3">
// //                     <Link
// //                       to={`/products/${product.slug}`}
// //                       className="inline-block px-4 py-1 text-sm font-medium bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition"
// //                     >
// //                       View Details
// //                     </Link>
// //                   </td> */}
// //                   <td className="px-6 py-3">
// //   <div className="flex items-center gap-3">

// //     {/* View */}
// //     <Link
// //       to={`/products/${product.slug}`}
// //       className="p-2 bg-blue-100 text-blue-600 rounded-lg hover:bg-blue-200 transition"
// //       title="View Product"
// //     >
// //       <FiEye size={18} />
// //     </Link>

// //     {/* Edit */}
// //     <Link
// //       to={`/products/edit/${product._id}`}
// //       className="p-2 bg-green-100 text-green-600 rounded-lg hover:bg-green-200 transition"
// //       title="Edit Product"
// //     >
// //       <FiEdit size={18} />
// //     </Link>

// //     {/* Delete */}
// //     <button
// //       onClick={() => handleDelete(product._id)}
// //       className="p-2 bg-red-100 text-red-600 rounded-lg hover:bg-red-200 transition"
// //       title="Delete Product"
// //     >
// //       <FiTrash size={18} />
// //     </button>

// //   </div>
// // </td>

// //                 </tr>
// //               ))}
// //             </tbody>
// //           </table>
// //         </div>
// //       )}
// //     </div>
// //   );
// // };

// // export default ProductList;

// import React, { useState } from "react";
// import { useGetProductsQuery } from "../../features/products/productAPI";
// import { Link } from "react-router-dom";
// import { FiEye, FiEdit, FiTrash } from "react-icons/fi";
// import Table from "../../components/common/Table";
// import Pagination from "../../components/common/Pagination";

// const ProductList = () => {
//   const [currentPage, setCurrentPage] = useState(1);
//   const perPage = 10;

//   const { data, isLoading, isError } = useGetProductsQuery({
//     page: currentPage,
//     limit: perPage,
//   });

//   const handleDelete = (id) => {
//     if (confirm("Are you sure you want to delete this product?")) {
//       console.log("Delete Product:", id);
//       // Later you will add RTK mutation here
//     }
//   };

//   const products = data?.data?.products || [];
//   const totalPages = Math.ceil(data?.data?.total / perPage || 0);

//   // Table columns
//   const columns = [
//     {
//       key: "sr",
//       label: "Sr. No",
//       render: (_, row, index) => index + 1,
//     },
//     {
//       key: "name",
//       label: "Name",
//     },
//      {
//       key: "stock",
//       label: "Stock",
//     },
//     {
//       key: "price",
//       label: "Price",
//       render: (_, row) => `₹${row.basePrice}`,
//     },
//     {
//       key: "status",
//       label: "Status",
//       render: (_, row) => (
//         <span
//           className={`px-2 py-1 text-xs font-semibold rounded-full ${
//             row.status === "active"
//               ? "bg-green-100 text-green-800"
//               : "bg-red-100 text-red-800"
//           }`}
//         >
//           {row.status}
//         </span>
//       ),
//     },
//     {
//       key: "views",
//       label: "Views",
//       render: (_, row) => row.viewCount,
//     },
//     {
//       key: "createdAt",
//       label: "Created At",
//       render: (_, row) => new Date(row.createdAt).toLocaleDateString(),
//     },
//   ];

//   // Action buttons
//   const rowActions = (row) => (
//     <div className="flex items-center justify-center gap-2">
//       <Link
//         to={`/products/${row.slug}`}
//         className="p-2 bg-blue-100 text-blue-600 rounded-lg hover:bg-blue-200 transition"
//         title="View"
//       >
//         <FiEye size={18} />
//       </Link>

//       <Link
//         to={`/products/edit/${row._id}`}
//         className="p-2 bg-green-100 text-green-600 rounded-lg hover:bg-green-200 transition"
//         title="Edit"
//       >
//         <FiEdit size={18} />
//       </Link>

//       <button
//         onClick={() => handleDelete(row._id)}
//         className="p-2 bg-red-100 text-red-600 rounded-lg hover:bg-red-200 transition"
//         title="Delete"
//       >
//         <FiTrash size={18} />
//       </button>
//     </div>
//   );

//   if (isLoading)
//     return (
//       <div className="text-center mt-10 text-gray-500">Loading products...</div>
//     );

//   if (isError)
//     return (
//       <div className="text-center mt-10 text-red-600">
//         Failed to load products.
//       </div>
//     );

//   return (
//     <div className="space-y-6">
//       {/* Header */}
//       <div className="flex items-center justify-between">
//         <h2 className="text-xl font-semibold text-gray-700">Products</h2>
//         <div className="flex items-center gap-3">
//           <input
//             type="text"
//             placeholder="Search products..."
//             className="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none w-60"
//           />
//           <Link
//             to="/products/add"
//             className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition"
//           >
//             + Add Product
//           </Link>
//         </div>
//       </div>

//       {/* Table */}
//       <Table columns={columns} data={products} actions={rowActions} />

//       {/* Pagination */}
//       <Pagination
//         currentPage={currentPage}
//         totalPages={totalPages}
//         onPageChange={(pg) => setCurrentPage(pg)}
//       />
//     </div>
//   );
// };

// export default ProductList;




import React, { useState, useRef, useEffect } from "react";
import { useGetProductsQuery } from "../../features/products/productAPI";
import { Link } from "react-router-dom";
import { FiEye, FiEdit, FiTrash, FiChevronDown, FiPackage } from "react-icons/fi";
import Table from "../../components/common/Table";
import Pagination from "../../components/common/Pagination";

// ─── Stock Status Config ────────────────────────────────────────────────────
const STOCK_CONFIG = {
  IN_STOCK:    { label: "In Stock",    bg: "bg-green-100",  text: "text-green-700",  dot: "bg-green-500"  },
  LOW:         { label: "Low",         bg: "bg-yellow-100", text: "text-yellow-700", dot: "bg-yellow-500" },
  CRITICAL:    { label: "Critical",    bg: "bg-orange-100", text: "text-orange-700", dot: "bg-orange-500" },
  OUT_OF_STOCK:{ label: "Out of Stock",bg: "bg-red-100",    text: "text-red-700",    dot: "bg-red-500"    },
};

// ─── Stock Badge ─────────────────────────────────────────────────────────────
const StockBadge = ({ status, stock, showCount = true }) => {
  const cfg = STOCK_CONFIG[status] || STOCK_CONFIG.OUT_OF_STOCK;
  return (
    <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${cfg.bg} ${cfg.text}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${cfg.dot}`} />
      {showCount ? `${stock} · ${cfg.label}` : cfg.label}
    </span>
  );
};

// ─── Stock Cell (handles both simple + variant products) ─────────────────────
const StockCell = ({ product }) => {
  const [open, setOpen] = useState(false);
  const dropdownRef = useRef(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handler = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    if (open) document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  const hasVariants = product.hasVariants && product.variantStock?.length > 0;

  // ── Non-variant: simple badge ────────────────────────────────────────────
  if (!hasVariants) {
    return (
      <StockBadge status={product.stockStatus} stock={product.totalStock} />
    );
  }

  // ── Variant product: expandable breakdown ────────────────────────────────
  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setOpen(!open)}
        className="inline-flex items-center gap-1 group focus:outline-none"
      >
        <StockBadge status={product.stockStatus} stock={product.totalStock} />
        <span className={`ml-0.5 text-gray-400 transition-transform duration-200 ${open ? "rotate-180" : ""}`}>
          <FiChevronDown size={13} />
        </span>
      </button>

      {open && (
        <div className="absolute z-30 top-8 left-0 bg-white border border-gray-200 rounded-xl shadow-xl p-3 min-w-[240px]">
          {/* Header */}
          <div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
            <FiPackage size={13} className="text-gray-400" />
            <span className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
              Variant Inventory
            </span>
          </div>

          {/* Variant rows */}
          <div className="space-y-2">
            {product.variantStock.map((v) => (
              <div key={v.variantId} className="flex items-center justify-between gap-3">
                {/* Left: size + color */}
                <div className="flex items-center gap-1.5 min-w-0">
                  <span className="text-xs font-medium text-gray-700 bg-gray-100 px-1.5 py-0.5 rounded">
                    {v.size}
                  </span>
                  <span className="text-xs text-gray-500 truncate">{v.color}</span>
                </div>
                {/* Right: stock badge */}
                <StockBadge status={v.stockStatus} stock={v.stock} />
              </div>
            ))}
          </div>

          {/* Total footer */}
          <div className="mt-2.5 pt-2 border-t border-gray-100 flex items-center justify-between">
            <span className="text-xs font-semibold text-gray-600">Total Stock</span>
            <span className="text-xs font-bold text-gray-800">{product.totalStock} units</span>
          </div>
        </div>
      )}
    </div>
  );
};

// ─── Main ProductList Page ────────────────────────────────────────────────────
const ProductList = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const perPage = 10;

  const { data, isLoading, isError } = useGetProductsQuery({
    page: currentPage,
    limit: perPage,
  });

  const handleDelete = (id) => {
    if (confirm("Are you sure you want to delete this product?")) {
      console.log("Delete Product:", id);
    }
  };

  const products = data?.data?.products || [];
  const totalPages = Math.ceil((data?.data?.pagination?.total || 0) / perPage);

  // ── Table columns ──────────────────────────────────────────────────────────
  const columns = [
    {
      key: "sr",
      label: "Sr.",
      render: (_, row, index) => (
        <span className="text-gray-400 text-sm">
          {(currentPage - 1) * perPage + index + 1}
        </span>
      ),
    },
    {
      key: "name",
      label: "Product",
      render: (_, row) => {
        const image =
          row.images?.gallery?.[0] ||
          row.images?.primary ||
          row.variantStock?.[0]?.images?.[0] ||
          null;
        return (
          <div className="flex items-center gap-3">
            {image ? (
              <img
                src={image}
                alt={row.name}
                className="w-9 h-9 rounded-lg object-cover border border-gray-100 flex-shrink-0"
                onError={(e) => { e.target.style.display = "none"; }}
              />
            ) : (
              <div className="w-9 h-9 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
                <FiPackage size={16} className="text-gray-400" />
              </div>
            )}
            <div className="min-w-0">
              <p className="text-sm font-medium text-gray-800 truncate max-w-[160px]">{row.name}</p>
              {row.hasVariants && (
                <p className="text-xs text-gray-400">{row.variantStock?.length || 0} variants</p>
              )}
            </div>
          </div>
        );
      },
    },
    {
      key: "inventory",
      label: "Inventory",
      render: (_, row) => <StockCell product={row} />,
    },
    {
      key: "price",
      label: "Price",
      render: (_, row) => (
        <span className="text-sm font-medium text-gray-700">₹{row.basePrice}</span>
      ),
    },
    {
      key: "status",
      label: "Status",
      render: (_, row) => (
        <span
          className={`px-2 py-1 text-xs font-semibold rounded-full ${
            row.status === "active"
              ? "bg-green-100 text-green-800"
              : row.status === "draft"
              ? "bg-gray-100 text-gray-600"
              : "bg-red-100 text-red-800"
          }`}
        >
          {row.status}
        </span>
      ),
    },
    {
      key: "views",
      label: "Views",
      render: (_, row) => (
        <span className="text-sm text-gray-500">{row.viewCount}</span>
      ),
    },
    {
      key: "createdAt",
      label: "Created",
      render: (_, row) => (
        <span className="text-sm text-gray-500">
          {new Date(row.createdAt).toLocaleDateString("en-IN", {
            day: "2-digit", month: "short", year: "numeric",
          })}
        </span>
      ),
    },
  ];

  // ── Row actions ────────────────────────────────────────────────────────────
  const rowActions = (row) => (
    <div className="flex items-center justify-center gap-2">
      <Link
        to={`/products/${row.slug}`}
        className="p-1.5 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition"
        title="View"
      >
        <FiEye size={15} />
      </Link>
      <Link
        to={`/products/edit/${row._id}`}
        className="p-1.5 bg-green-50 text-green-600 rounded-lg hover:bg-green-100 transition"
        title="Edit"
      >
        <FiEdit size={15} />
      </Link>
      <button
        onClick={() => handleDelete(row._id)}
        className="p-1.5 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition"
        title="Delete"
      >
        <FiTrash size={15} />
      </button>
    </div>
  );

  if (isLoading)
    return <div className="text-center mt-10 text-gray-500">Loading products...</div>;

  if (isError)
    return <div className="text-center mt-10 text-red-600">Failed to load products.</div>;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-semibold text-gray-700">Products</h2>
        <div className="flex items-center gap-3">
          <input
            type="text"
            placeholder="Search products..."
            className="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-400 outline-none w-60 text-sm"
          />
          <Link
            to="/products/add"
            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition text-sm"
          >
            + Add Product
          </Link>
        </div>
      </div>

      {/* Inventory Summary Bar */}
      <InventorySummary products={products} />

      {/* Table */}
      <Table columns={columns} data={products} actions={rowActions} />

      {/* Pagination */}
      <Pagination
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={(pg) => setCurrentPage(pg)}
      />
    </div>
  );
};

// ─── Inventory Summary Bar ────────────────────────────────────────────────────
const InventorySummary = ({ products }) => {
  const stats = products.reduce(
    (acc, p) => {
      const s = p.stockStatus;
      if (s === "IN_STOCK") acc.inStock++;
      else if (s === "LOW") acc.low++;
      else if (s === "CRITICAL") acc.critical++;
      else if (s === "OUT_OF_STOCK") acc.outOfStock++;
      return acc;
    },
    { inStock: 0, low: 0, critical: 0, outOfStock: 0 }
  );

  const items = [
    { label: "In Stock",     value: stats.inStock,    color: "text-green-600",  bg: "bg-green-50",  border: "border-green-200" },
    { label: "Low Stock",    value: stats.low,         color: "text-yellow-600", bg: "bg-yellow-50", border: "border-yellow-200" },
    { label: "Critical",     value: stats.critical,    color: "text-orange-600", bg: "bg-orange-50", border: "border-orange-200" },
    { label: "Out of Stock", value: stats.outOfStock,  color: "text-red-600",    bg: "bg-red-50",    border: "border-red-200" },
  ];

  return (
    <div className="grid grid-cols-4 gap-3">
      {items.map((item) => (
        <div
          key={item.label}
          className={`flex items-center justify-between px-4 py-3 rounded-xl border ${item.bg} ${item.border}`}
        >
          <span className="text-xs font-medium text-gray-600">{item.label}</span>
          <span className={`text-lg font-bold ${item.color}`}>{item.value}</span>
        </div>
      ))}
    </div>
  );
};

export default ProductList;