"use client";

import {
  useReactTable,
  getCoreRowModel,
  flexRender,
} from "@tanstack/react-table";
import styles from "./TanStackTable.module.scss";
import { useEffect, useState } from "react";
import ReviewModal from "../reviewModal/ReviewModal";

const TanStackTable = ({ data }: any) => {
  const [tableData, setTableData] = useState([]);
  const [open, setOpen] = useState(false);
  const [reviewModalData, setReviewModalData] = useState([]);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  /** Set Title and api data object key for the Table title and data */
  const columns: any = [
    {
      header: "ID",
      accessorKey: "id",
    },
    {
      header: "Title",
      accessorKey: "title",
    },
    {
      header: "Description",
      accessorKey: "description",
    },
    {
      header: "Category",
      accessorKey: "category",
    },
    {
      header: "Price",
      accessorKey: "price",
    },
    {
      header: "Discount Percentage",
      accessorKey: "discountPercentage",
    },
    {
      header: "Rating",
      accessorKey: "rating",
    },
    {
      header: "Stock",
      accessorKey: "stock",
    },
    {
      header: "Tags",
      accessorKey: "tags",
    },
    {
      header: "Brand",
      accessorKey: "brand",
    },
    {
      header: "Reviews",
      accessorKey: "reviews",
      cell: ({ row }: any) => (
        <>
          {/* {row.original.reviews.length} Reviews */}
          <button onClick={() => handleButtonClick(row.original)}>
            View Reviews ({row.original.reviews.length})
          </button>
        </>
      ),
    },
  ];

  /** Send Review array to Review Modal before openning */
  const handleButtonClick = (rowData: any) => {
    setReviewModalData(rowData?.reviews);
    handleOpen();
    // console.log("Button clicked for row:", rowData?.reviews);
  };

  const table = useReactTable({
    data: tableData,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  useEffect(() => {
    setTableData(data?.products);
    console.log("Server data", data);
  }, [data]);

  return (
    <>
      <div className="w3-container">
        <table className="w3-table-all">
          <thead>
            {table.getHeaderGroups().map((headerGroup: any) => (
              <tr key={headerGroup?.id}>
                {headerGroup.headers.map((header: any) => (
                  <th key={header?.id}>
                    {flexRender(
                      header.column.columnDef.header,
                      header.getContext()
                    )}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody>
            {table.getRowModel().rows.map((row: any) => (
              <tr key={row.id}>
                {row.getVisibleCells().map((cell: any) => (
                  <td key={cell.id}>
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <ReviewModal
        open={open}
        handleClose={handleClose}
        reviewModalData={reviewModalData}
      />
    </>
  );
};

export default TanStackTable;
