// Components/DataTable.jsx
// Reusable styled table component with compact design
import React, { useRef } from "react";
import { Column } from "primereact/column";
import { Button } from "primereact/button";
import { Menu } from "primereact/menu";
import ServerSideDataTable from "@/Components/ServerSideDataTable";

// Reusable Action Menu Component
const ActionMenu = ({ rowData, actions, permission, context }) => {
  const menuRef = useRef(null);
  const menuItems = [];

  if (actions && Array.isArray(actions)) {
    actions.forEach((action) => {
      // Check permission if provided
      if (action.permission && !permission.includes(action.permission)) {
        return;
      }
      // Optional visibility: show(rowData) must be true if provided
      if (typeof action.show === "function" && !action.show(rowData)) {
        return;
      }

      menuItems.push({
        label: action.label,
        icon: action.icon,
        command: () => {
          if (action.handler) {
            action.handler(rowData, context);
          }
        },
      });
    });
  }

  if (menuItems.length === 0) return null;

  return (
    <>
      <Button
        icon="pi pi-ellipsis-v"
        onClick={(e) => menuRef.current.toggle(e)}
        className="p-button-text p-button-rounded p-button-plain"
        aria-label="Actions"
      />
      <Menu
        ref={menuRef}
        model={menuItems}
        popup
        id={`action_menu_${rowData.id}`}
      />
    </>
  );
};

const DataTable = ({
  fetchUrl,
  children,
  columns,
  emptyMessage = "No records found.",
  headerActions,
  extraParams = {},
  className = "data-table",
  ...otherProps
}) => {
  // Render columns from config array if provided
  const renderColumns = () => {
    if (columns && Array.isArray(columns)) {
      return columns.map((col, index) => {
        if (col.type === "action" && col.actions) {
          // Action column with configurable actions
          return (
            <Column
              key={col.field || `action-${index}`}
              header={col.header || "Action"}
              body={(rowData) => {
                return (
                  <ActionMenu
                    rowData={rowData}
                    actions={col.actions}
                    permission={col.permission}
                    context={col.context}
                  />
                );
              }}
              dataType={col.dataType || "boolean"}
              bodyClassName={col.bodyClassName || "text-center"}
              style={col.style || { width: "100px" }}
            />
          );
        }

        // Regular column
        return (
          <Column
            key={col.field || index}
            field={col.field}
            header={col.header}
            body={col.body}
            style={col.style}
            headerStyle={col.headerStyle}
            {...col.props}
          />
        );
      });
    }
    return children;
  };

  return (
    <>
      <style>{`
        .data-table .p-datatable-thead > tr > th,
        .table-compact-style .p-datatable-thead > tr > th {
          padding: 0.5rem 0.75rem !important;
          font-size: 0.8125rem;
          font-weight: 500;
          text-align: center !important;
          background-color: transparent !important;
          background: transparent !important;
          border-bottom: 1px solid rgba(0, 0, 0, 0.1) !important;
        }
        .data-table .p-datatable-header,
        .table-compact-style .p-datatable-header {
          background-color: transparent !important;
          background: transparent !important;
          border: none !important;
          border-bottom: none !important;
        }
        .data-table .p-datatable-thead > tr > th .p-column-header-content,
        .table-compact-style .p-datatable-thead > tr > th .p-column-header-content {
          justify-content: center !important;
          display: flex !important;
        }
        .data-table .p-datatable-tbody > tr > td,
        .table-compact-style .p-datatable-tbody > tr > td {
          padding: 0rem 0.75rem !important;
          font-size: 0.775rem;
          vertical-align: middle;
        }
        .data-table .p-datatable-tbody > tr,
        .table-compact-style .p-datatable-tbody > tr {
          transition: background-color 0.15s ease;
        }
        .data-table .p-datatable-tbody > tr:hover,
        .table-compact-style .p-datatable-tbody > tr:hover {
          background-color: rgba(0, 0, 0, 0.02);
        }
      `}</style>
      <ServerSideDataTable
        fetchUrl={fetchUrl}
        emptyMessage={emptyMessage}
        headerActions={headerActions}
        extraParams={extraParams}
        className={className}
        {...otherProps}
      >
        {renderColumns()}
      </ServerSideDataTable>
    </>
  );
};

export default DataTable;
