import MUIDataTable from "mui-datatables";
import { useEffect, useState } from "react";
import { PropTypes } from "prop-types";
import { Box } from "@mui/system";
import { Tooltip } from "@mui/material";
export const SimpleTable = ({
  columns,
  data,
  name,
  responsive,
  cssClass,
  headerColor,
  rowColors,
}) => {
  const [rows, setRows] = useState(data);

  useEffect(() => {
    setRows(data);
  }, [data]);

  useEffect(() => {
    const d = data?.map((item) => {
      return item?.map((row) => {
        if (!row && row !== 0) {
          return "";
        } else {
          return row;
        }
      });
    });
    setRows(d);
  }, [data]);
  const options = {
    viewColumns: false,
    search: false,
    sort: false,
    pagination: false,
    filter: false,
    print: false,
    download: false,
    selectableRowsHeader: false,
    selectableRowsHideCheckboxes: true,
    responsive: responsive || "vertical",
    fixedHeader: true,
    tableBodyMaxHeight: { xs: "auto", md: "70vh" },
    setRowProps: (row, dataIndex) => ({
      style: rowColors
        ? { backgroundColor: rowColors[dataIndex % rowColors.length] }
        : {},
    }),

    // localization
    textLabels: {
      body: {
        noMatch: "داده ای جهت نمایش موجود نیست!",
        toolTip: "مرتب سازی",
        columnHeaderTooltip: (column) => `مرتب سازی بر اساس ${column.label}`,
      },
      pagination: {
        next: "صفحه بعد",
        previous: "صفحه قبل",
        rowsPerPage: "تعداد سطر در هر صفحه:",
        displayRows: "تعداد کل نتایج: ",
      },
      toolbar: {
        search: "جستجو",
        downloadCsv: "دانلود CSV",
        print: "پرینت",
        viewColumns: "نمایش سطون ها",
        filterTable: "فیلتر جدول",
      },
      filter: {
        all: "همه",
        title: "فیلترها",
        reset: "پاکسازی",
      },
      viewColumns: {
        title: "نمایش ستون ها",
        titleAria: "نمایش/بستن ستون های جدول",
      },
      selectedRows: {
        text: "سطر انتخاب شده است",
        delete: "پاک کردن",
        deleteAria: "پاک کردن سطرهای انتخاب شده",
      },
    },
  };
  const columnsWithHeaderColor = columns.map((col, colIndex) => ({
    name: col,
    options: {
      customHeadRender: (columnMeta) => {
        let sumValue = 0;
        rows?.forEach((row) => {
          let value = row[colIndex];
          if (typeof value === "string") {
            const cleaned = value.replace(/,/g, "");
            value = parseFloat(cleaned);
          }
          if (!isNaN(value)) sumValue += value;
        });

        const tooltipTitle =
          sumValue && !isNaN(sumValue)
            ? `مجموع: ${sumValue.toLocaleString()}`
            : "";

        return (
          <Tooltip title={tooltipTitle} arrow placement="top">
            <th
              key={columnMeta.index}
              style={{
                backgroundColor: headerColor || "#e3e3e3",
                fontSize: "14px",
                padding: "10px",
                textAlign: "center",
                cursor: tooltipTitle ? "help" : "default",
              }}
            >
              {columnMeta.name}
            </th>
          </Tooltip>
        );
      },
    },
  }));

  return (
    <Box className={`simple-table ${cssClass}`} width={"100%"}>
      <MUIDataTable
        title={name}
        data={rows}
        columns={columnsWithHeaderColor}
        options={options}
      />
    </Box>
  );
};

SimpleTable.propTypes = {
  columns: PropTypes.any,
  data: PropTypes.any,
  name: PropTypes.any,
  expandable: PropTypes.bool,
  responsive: PropTypes.any,
  headerColor: PropTypes.string,
  rowColors: PropTypes.string,
};
