"use client";

import React from "react";
import {
  deleteProductCollection,
  getProductCollections,
} from "@/Services/ProductCollections/ApiProductCollections";
import { DataTable } from "@/components/ui/DataTableNew";
import { useModal } from "@/context/ModalProvider";
import { Button } from "@/components/ui/button";
import Image from "next/image";
import AddProductCollections from "./AddProductCollections";

const ProductCollections = () => {
  const { openModal } = useModal();

  const handleClick = (url) => {
    openModal(
      <div className="w-full h-full flex justify-center items-center">
        <Image
          src={url?.replace("/api", "")}
          alt="Product Collection"
          width={600}
          height={600}
          className="max-h-fit object-contain"
          loading="lazy"
        />
      </div>
    );
  };

  const columns = [
    {
      header: "Name",
      accessorKey: "name",
      enableHiding: false,
    },
    {
      header: "Offers",
      accessorKey: "offers_percentage",
      cell: (info) => (info.getValue() ? info.getValue() + "%" : "-"),
    },

    {
      header: "Target",
      accessorKey: "url_target",
      cell: (info) => info.getValue()?.toUpperCase(),
    },
    {
      header: "Image",
      cell: (info) =>
        info.row.original.image ? (
          <Button
            variant="ghost"
            className="h-8 w-8 p-0"
            onClick={() => handleClick(info.row.original.image)}
          >
            <span className="sr-only">View Image</span>
            <Image
              src={info.row.original.image?.replace("/api", "")}
              alt="Collection"
              width={50}
              height={50}
              className="rounded"
              loading="lazy"
            />
          </Button>
        ) : (
          "No Image"
        ),
    },
    {
      header: "Description",
      accessorKey: "description",
      cell: (info) => (info.getValue() ? info.getValue() : "N/A"),
    },
    {
      header: "Status",
      accessorKey: "status",
      cell: (info) => (info.getValue() ? "Active" : "Inactive"),
    },
  ];

  const searchFields = [
    { key: "name", type: "text", single: false },
    { key: "url", type: "text", single: false },
    { key: "url_target", type: "select" },
  ];

  return (
    <div>
      <AddProductCollections />

      <DataTable
        title="Manage Product Collections"
        fetchData={getProductCollections}
        columnsConfig={columns}
        tag="product_collections"
        // searchFields={searchFields}
        onDelete={deleteProductCollection}
        EditComponent={AddProductCollections}
      />
    </div>
  );
};

export default ProductCollections;
