"use client";
import * as React from "react";
import { Card, CardHeader, CardContent, SxProps, Theme } from "@mui/material";
import { DataGrid, GridColDef, GridRowSelectionModel, GridColumnGroupingModel, useGridApiRef} from "@mui/x-data-grid";
import { darken, lighten, styled } from "@mui/material/styles";
import { useState } from "react";

interface CustomDatagridProps {
  Title?: string;
  rows: any[];
  columns: any[];
  columnWidth?: number;
  Style?: boolean;
  sx?: SxProps<Theme>;
  dataGridHeight?: number | string;
  [key: string]: any;
  checkboxSelection?: boolean;
  onRowClick?: any;
  onRowSelectionModelChange?: (
    newSelectionModel: GridRowSelectionModel,
  ) => void;
  selectionModel?: GridRowSelectionModel;
  rowSelectionModel?: GridRowSelectionModel;
  columnGroupingModel?: any;
  pageSize?:any;
}

const CustomDatagrid: React.FC<CustomDatagridProps> = ({
  Title,
  rows,
  columns,
  columnWidth,
  Style = false,
  sx,
  dataGridHeight,
  checkboxSelection, // Destructure the new prop
  rowSelectionModel,
  onRowSelectionModelChange, // Destructure the new prop
  selectionModel,
  onRowClick,
  columnGroupingModel,
  pageSize,
  ...props
}) => {
  const modifiedColumns = columns.map((column) => {
    return {
      ...column,
      width: columnWidth ?? 150,
    };
  });

  const rowsWithDefaultValues = rows.map((row) => {
    return { ...row };
  });

  // Event handler to be called when the selection changes
  const handleSelectionModelChange = (
    newSelectionModel: GridRowSelectionModel,
  ) => {
    // setSelectionModel(newSelectionModel);
    // To log selected row data, filter rows based on the new selection model
    const selectedRowsData = rows.filter((row) =>
      newSelectionModel.includes(row.id),
    );
    console.log(selectedRowsData);
  };

  const getBackgroundColor = (color: string, mode: "light" | "dark") =>
    mode === "dark" ? darken(color, 0.7) : lighten(color, 0.7);

  const getHoverBackgroundColor = (color: string, mode: "light" | "dark") =>
    mode === "dark" ? darken(color, 0.6) : lighten(color, 0.6);

  const getSelectedBackgroundColor = (color: string, mode: "light" | "dark") =>
    mode === "dark" ? darken(color, 0.5) : lighten(color, 0.5);

  const getSelectedHoverBackgroundColor = (
    color: string,
    mode: "light" | "dark",
  ) => (mode === "dark" ? darken(color, 0.4) : lighten(color, 0.4));

  const StyledDataGrid = styled(DataGrid)(({ theme }) => ({
    "& .super-app-theme--Open": {
      backgroundColor: getBackgroundColor(
        theme.palette.info.main,
        theme.palette.mode,
      ),
      "&:hover": {
        backgroundColor: getHoverBackgroundColor(
          theme.palette.info.main,
          theme.palette.mode,
        ),
      },
      "&.Mui-selected": {
        backgroundColor: getSelectedBackgroundColor(
          theme.palette.info.main,
          theme.palette.mode,
        ),
        "&:hover": {
          backgroundColor: getSelectedHoverBackgroundColor(
            theme.palette.info.main,
            theme.palette.mode,
          ),
        },
      },
    },
    "& .super-app-theme--finish": {
      backgroundColor: getBackgroundColor(
        theme.palette.success.main,
        theme.palette.mode,
      ),
      "&:hover": {
        backgroundColor: getHoverBackgroundColor(
          theme.palette.success.main,
          theme.palette.mode,
        ),
      },
      "&.Mui-selected": {
        backgroundColor: getSelectedBackgroundColor(
          theme.palette.success.main,
          theme.palette.mode,
        ),
        "&:hover": {
          backgroundColor: getSelectedHoverBackgroundColor(
            theme.palette.success.main,
            theme.palette.mode,
          ),
        },
      },
    },
    "& .super-app-theme--danger": {
      backgroundColor: getBackgroundColor(
        theme.palette.warning.main,
        theme.palette.mode,
      ),
      "&:hover": {
        backgroundColor: getHoverBackgroundColor(
          theme.palette.warning.main,
          theme.palette.mode,
        ),
      },
      "&.Mui-selected": {
        backgroundColor: getSelectedBackgroundColor(
          theme.palette.warning.main,
          theme.palette.mode,
        ),
        "&:hover": {
          backgroundColor: getSelectedHoverBackgroundColor(
            theme.palette.warning.main,
            theme.palette.mode,
          ),
        },
      },
    },
    "& .super-app-theme--warning": {
      backgroundColor: getBackgroundColor(
        theme.palette.error.main,
        theme.palette.mode,
      ),
      "&:hover": {
        backgroundColor: getHoverBackgroundColor(
          theme.palette.error.main,
          theme.palette.mode,
        ),
      },
      "&.Mui-selected": {
        backgroundColor: getSelectedBackgroundColor(
          theme.palette.error.main,
          theme.palette.mode,
        ),
        "&:hover": {
          backgroundColor: getSelectedHoverBackgroundColor(
            theme.palette.error.main,
            theme.palette.mode,
          ),
        },
      },
    },
  }));

  return (
    <div
      className="mt-5 mb-5"
      style={{ height: dataGridHeight ?? 400, width: "100%" }}
    >
      {Title ? (
        <Card style={{ marginRight: 10 }}>
          {Title && <CardHeader className="text-slate-500" title={Title} />}
          <CardContent
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              marginTop: -20,
            }}
          >
            {Style ? (
              <StyledDataGrid
                rows={rowsWithDefaultValues}
                columns={modifiedColumns}
                editMode="row"
                getRowHeight={() => 'auto'}
                onRowClick={onRowClick}
                checkboxSelection={checkboxSelection}
                rowSelectionModel={rowSelectionModel}
                onRowSelectionModelChange={onRowSelectionModelChange}
                experimentalFeatures={{ columnGrouping: true }}
                columnGroupingModel={columnGroupingModel}
                initialState={{
                  pagination: { paginationModel: { pageSize: 10 } },
                }}
                className="customDataGrid"
                sx={{
                  boxShadow: 1,
                  border: 0,
                  borderColor: "primary.light",
                  "& .MuiDataGrid-cell:hover": {
                    color: "primary.main",
                  },
                  height: dataGridHeight ?? 400,
                  "& .MuiDataGrid-root": {
                    overflow: "auto",
                  },
                  "& .MuiDataGrid-columnHeaderTitle": {
                    fontWeight: "bold",
                  },
                  ...sx,
                }}
                {...props}
              />
            ) : (
              <DataGrid
                rows={rowsWithDefaultValues}
                columns={modifiedColumns}
                editMode="row"
                getRowHeight={() => 'auto'}
                onRowClick={onRowClick}
                checkboxSelection={checkboxSelection}
                rowSelectionModel={rowSelectionModel}
                onRowSelectionModelChange={onRowSelectionModelChange}
                experimentalFeatures={{ columnGrouping: true }}
                columnGroupingModel={columnGroupingModel}
                initialState={{
                  pagination: { paginationModel: { pageSize: 10 } },
                }}
                className="customDataGrid"
                sx={{
                  boxShadow: 2,
                  border: 2,
                  borderColor: "primary.light",
                  "& .MuiDataGrid-cell:hover": {
                    color: "primary.main",
                  },
                  height: 300,
                  "& .MuiDataGrid-root": {
                    overflow: "auto",
                  },
                  ...sx,
                }}
                {...props}
              />
            )}
          </CardContent>
        </Card>
      ) : Style ? (
        <StyledDataGrid
          rows={rowsWithDefaultValues}
          columns={modifiedColumns}
          editMode="row"
          getRowHeight={() => 'auto'}
          onRowClick={onRowClick}
          checkboxSelection={checkboxSelection}
          rowSelectionModel={rowSelectionModel}
          onRowSelectionModelChange={onRowSelectionModelChange}
          experimentalFeatures={{ columnGrouping: true }}
          columnGroupingModel={columnGroupingModel}
          style={{ marginRight: 20 }}
          initialState={{
            pagination: { paginationModel: { pageSize: 10 } },
          }}
          className="customDataGrid"
          sx={{
            boxShadow: 1,
            border: 0,
            borderColor: "primary.light",
            "& .MuiDataGrid-cell:hover": {
              color: "primary.main",
            },
            height: dataGridHeight ?? 400,
            "& .MuiDataGrid-root": {
              overflow: "auto",
            },
            "& .MuiDataGrid-columnHeaderTitle": {
              fontWeight: "bold",
            },
            ...sx,
          }}
          {...props}
        />
      ) : (
        <DataGrid
          rows={rowsWithDefaultValues}
          columns={modifiedColumns}
          editMode="row"
          getRowHeight={() => 'auto'}
          onRowClick={onRowClick}
          style={{ marginRight: 0 }}
          checkboxSelection={checkboxSelection}
          rowSelectionModel={rowSelectionModel}
          onRowSelectionModelChange={onRowSelectionModelChange}
          experimentalFeatures={{ columnGrouping: true }}
          columnGroupingModel={columnGroupingModel}
          initialState={{
            pagination: { paginationModel: { pageSize: pageSize ?? 10 } },
          }}
          className="customDataGrid"
          sx={{
            boxShadow: 2,
            border: 2,
            borderColor: "primary.light",
            "& .MuiDataGrid-cell:hover": {
              color: "primary.main",
            },
            height: dataGridHeight ?? 300,
            "& .MuiDataGrid-root": {
              overflow: "auto",
            },
            ...sx,
          }}
          {...props}
        />
      )}
    </div>
  );
};

export default CustomDatagrid;
