"use client";

import React from "react";
import AddProduct from "./AddProducts";

import { deleteProducts, getProducts } from "@/Services/Products/ApiProducts";
import { DataTable } from "@/components/ui/DataTableNew";
import { useModal } from "@/context/ModalProvider";
import { Button } from "@/components/ui/button";
import Image from "next/image";

const Products = () => {
  const { openModal } = useModal();
  const handleClick = (url) => {
    openModal(
      <div className="w-full h-full flex justify-center items-center">
        <Image
          src={url?.replace("/api", "")}
          alt="Testimonial"
          width={600}
          height={600}
          className="max-h-fit object-contain"
          loading="lazy"
        />
      </div>
    );
  };
  const columns = [
    {
      header: "Name",
      accessorKey: "name",
      enableSorting: true,
      enableHiding: false,
    },
    {
      header: "Category",
      accessorKey: "category_name",
    },

    {
      header: "Image",
      cell: (info) => {
        const images = info.row.original.product_image?.split(",") || [];

        return images.length > 0 ? (
          <div className="flex flex-wrap gap-1">
            {images.map((img, idx) => (
              <Button
                key={idx}
                variant="ghost"
                className="h-8 w-8 p-0"
                onClick={() => handleClick(img)}
              >
                <Image
                  src={img?.replace("/api", "")}
                  alt={`product-${idx}`}
                  width={40}
                  height={40}
                  className="rounded"
                  loading="lazy"
                />
              </Button>
            ))}
          </div>
        ) : (
          "No Image"
        );
      },
    },

    {
      header: "Description",
      accessorKey: "description",
    },
    {
      header: "Status",
      accessorKey: "status",
      cell: (info) => {
        return info.getValue() == 1 ? "Actiive" : "In Active";
      },
    },
  ];
  const searchFields = [
    {
      key: "name",
      type: "text",
      single: false,
    },
    {
      key: "category_name",
      type: "text",
      single: false,
    },
    {
      key: "status",
      type: "select",
    },
  ];

  return (
    <div>
      <AddProduct />

      <DataTable
        title="Manage Products"
        fetchData={getProducts}
        columnsConfig={columns}
        tag="products"
        searchFields="name"
        onDelete={deleteProducts}
        EditComponent={AddProduct}
        refresh 
      />
    </div>
  );
};

export default Products;
