"use client";

import { FC } from "react";
import { Box } from "@mui/material";
import {
  DataGridPro,
  GridColDef,
  GridColumnVisibilityModel,
  GridRowSelectionModel,
} from "@mui/x-data-grid-pro";
import { useCookies } from "react-cookie";

interface StyledDataGridProps {
  name: string;
  columns: GridColDef[];
  rows: any[];
  // eslint-disable-next-line no-unused-vars
  onRowClick?: (row: any) => void;
  height?: string;
  selectedRows?: GridRowSelectionModel;
  // eslint-disable-next-line no-unused-vars
  setSelectedRows?: (rows: GridRowSelectionModel) => void;
}

export const StyledDataGrid: FC<StyledDataGridProps> = ({
  name,
  columns,
  rows,
  onRowClick,
  height = "calc(100vh - 20px)",
  selectedRows,
  setSelectedRows,
}) => {
  const cookieName = `${name}DataGridColumnState`;
  const [cookies, setCookie] = useCookies([cookieName]);
  const handleColumnVisibilityChange = (model: GridColumnVisibilityModel) =>
    setCookie(cookieName, model, { path: "/" });

  return (
    <Box
      sx={{
        backgroundColor: "#ddd",
        border: 0,
        width: "100%",
        height,
        ".MuiDataGrid-row:nth-of-type(1n)": {
          backgroundColor: "#f3f3f3",
        },
        ".MuiDataGrid-row:nth-of-type(2n)": {
          backgroundColor: "#fff",
        },
        ".MuiDataGrid-columnHeaderTitle": {
          color: "#333",
          fontWeight: "bold",
          fontSize: 11,
          margin: "0 auto",
        },
        ".MuiDataGrid-columnHeader": {
          backgroundColor: "#ccc",
          border: 0,
          borderBottom: "3px solid #ddd",
        },
      }}
    >
      <DataGridPro
        rows={rows}
        columns={columns}
        density="compact"
        hideFooter
        sx={{ height }}
        rowBuffer={30}
        checkboxSelection={!!setSelectedRows}
        onRowSelectionModelChange={setSelectedRows}
        rowSelectionModel={selectedRows}
        rowHeight={46}
        scrollbarSize={0}
        disableVirtualization
        columnVisibilityModel={
          (cookies[cookieName] as GridColumnVisibilityModel) ?? undefined
        }
        onColumnVisibilityModelChange={handleColumnVisibilityChange}
        onRowClick={onRowClick}
      />
    </Box>
  );
};
