
import React from 'react';
import { DataGrid, GridOverlay, GridPagination, GridToolbarProps } from '@mui/x-data-grid';
import { makeStyles } from '@mui/styles';
import CustomToolBar from './CustomToolbar';
import {
  Box,
  GlobalStyles,
  Typography,
  useTheme,
  useMediaQuery,
} from '@mui/material';
import DataGridProps from '../interfaces/DataGridProps';
import SkeletonLoader from './SkeletonLoader';

const useStyles = makeStyles({
  virtualScrollerContent: {
    paddingTop: '0px',
  },
});

const DataGrids: React.FC<DataGridProps> = ({
  rows,
  columns,
  components,
  style,
  toolbar = true,
  pageSizeOptions,
  paginationModel,
  rowCount,
  onPaginationModelChange,
  onSearchQueryChange,
  searchQuery,
  paginationMode,
  loading,
  getRowId,
  width = '100%',
  height = '70vh',
  ...props
}) => {
  const classes = useStyles();
  const theme = useTheme();
  const screenHeight = window.innerHeight;
  const screenWidth = window.innerWidth;

  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const isTablet = useMediaQuery(theme.breakpoints.between('sm', 'md'));

  const getRowClassName = (params: any) => {
    return params.index % 2 === 0 ? 'even-row' : 'odd-row';
  };

  function CustomNoRowsOverlay() {
    return (
      <GridOverlay>
        <Typography
          variant={isMobile ? 'body2' : 'h6'}
          component='p'
          gutterBottom
          sx={{ mt: 1, fontSize: '0.875rem' }}
        >
          {rows.length === 0 && searchQuery ? 'No match found' : 'No rows'}
        </Typography>
      </GridOverlay>
    );
  }

  if (screenHeight > 1500) {
    height = 'auto';
  } else if (screenHeight > 1000) {
    height = 'auto';
  } else if (screenHeight === 642 && screenWidth === 768) {
    height = 'auto';
  } else if (screenHeight < 800 && screenHeight > 650) {
    height = 'auto';
  }

  return (
    <Box
      sx={{
        width: '100%',
        maxWidth: '100%',
        height: {
          xs: toolbar ? 'calc(100vh - 180px)' : 'calc(100vh - 120px)',
          sm: toolbar ? 'calc(100vh - 200px)' : 'calc(100vh - 140px)',
          md: toolbar ? 'calc(90vh - 220px)' : 'calc(90vh - 160px)',
        },
        minHeight: '250px',
        position: 'relative',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <GlobalStyles
        styles={{
          '::-webkit-scrollbar': {
            width: '8px',
            height: '8px',
          },
          '::-webkit-scrollbar-thumb': {
            backgroundColor: '#C4E0E9',
            borderRadius: '10px',
          },
          '::-webkit-scrollbar-track': {
            backgroundColor: '#f1f1f1',
          },
          '.MuiDataGrid-virtualScroller': {
            // overflowX: 'auto',
            flex: '1 1 auto',
          },
          '.MuiDataGrid-columnHeaders': {
            minHeight: isMobile ? '40px !important' : '48px !important',
            height: isMobile ? '40px !important' : '48px !important',
          },
          '.MuiDataGrid-cell': {
            padding: isMobile
              ? '4px !important'
              : isTablet
              ? '6px !important'
              : '8px !important',
          },
          '.MuiDataGrid-row': {
            minHeight: isMobile ? '36px !important' : '44px !important',
          },
          [theme.breakpoints.down('sm')]: {
            '.MuiTablePagination-selectLabel': {
              display: 'none !important',
            },
            '.MuiTablePagination-select': {
              display: 'none !important',
            },
            '.MuiTablePagination-spacer': {
              display: 'none !important',
            },
            '.MuiTablePagination-actions': {
              display: 'flex !important',
              marginLeft: '0 !important',
              alignItems: 'center',
            },
          },
        }}
      />
      <DataGrid
        rows={rows}
        columns={columns}
        components={{
          Toolbar: (props: GridToolbarProps) =>
            toolbar ? (
              <CustomToolBar
                {...props}
                searchQuery={searchQuery || ''}
                onSearchQueryChange={onSearchQueryChange}
                sx={{
                  flexDirection: isMobile ? 'column' : 'row',
                  gap: isMobile ? 1 : 2,
                  padding: isMobile ? '8px' : '12px',
                  width: '100%',
                  '& .MuiTextField-root': {
                    width: isMobile ? '100%' : '200px',
                    '& .MuiInputBase-input': {
                      fontSize: '0.875rem',
                    },
                  },
                  '& .MuiButton-root': {
                    fontSize: '0.875rem',
                    padding: isMobile ? '4px 8px' : '6px 12px',
                  },
                }}
              />
            ) : null,
          NoRowsOverlay: CustomNoRowsOverlay,
          Pagination: GridPagination,
          ...components,
        }}
        paginationModel={paginationModel}
        rowCount={rowCount}
        paginationMode={paginationMode || 'server'}
        onPaginationModelChange={onPaginationModelChange}
        pageSizeOptions={pageSizeOptions || [5, 10, 20, 30]}
        style={{ ...style }}
        loading={loading}
        getRowClassName={getRowClassName}
        classes={{ virtualScrollerContent: classes.virtualScrollerContent }}
        disableRowSelectionOnClick
        getRowId={getRowId}
        {...props}
        sx={{
          width: '100%',
          maxWidth: '100%',
          backgroundColor: '#FFFFFF',
          color: '#333333',
          border: '1px solid #E0E0E0',
          borderRadius: '4px',
          flex: '1 1 auto',
          display: 'flex',
          flexDirection: 'column',
          // overflow: 'auto',
          '& .MuiDataGrid-root': {
            width: '100% !important',
            maxWidth: '100% !important',
            fontSize: '0.875rem',
            borderBottom: '1px solid rgba(224, 224, 224, 1)',
          },
          '& .MuiDataGrid-columnHeaders': {
            backgroundColor: '#EEF2F6',
            color: '#000000',
            fontSize: '0.875rem',
            borderBottom: '1px solid rgba(224, 224, 224, 1)',
          },
          '& .MuiDataGrid-columnHeaderTitle': {
            color: '#000000',
            fontWeight: 500,
            fontSize: '0.875rem',
          },
          '& .MuiDataGrid-cell': {
            borderBottom: '1px solid #E0E0E0',
            fontSize: '0.875rem',
          },
          '& .MuiDataGrid-cell:first-of-type': {
      paddingLeft: '30px !important', 
    },
    '& .MuiDataGrid-columnHeader:first-of-type': {
      paddingLeft: '30px !important', 
    },
          '& .MuiDataGrid-footerContainer': {
            minHeight: '56px',
            fontSize: '0.875rem',
            '& .MuiSelect-select': {
              fontSize: '0.875rem',
            },
          },
          '@media (max-width: 425px) and (max-height: 608px)': {
            '& .MuiDataGrid-root': {
              minWidth: '100%',
            },
            '& .MuiDataGrid-cell': {
              whiteSpace: 'normal',
              // overflow: 'visible',
            },
            '& .MuiDataGrid-toolbarContainer': {
              display: 'flex',
              flexDirection: 'column',
              gap: '8px',
            },
            '& .MuiTablePagination-selectLabel': {
              display: 'block',
            },
            '& .MuiTablePagination-select': {
              minHeight: '32px',
              fontSize: '0.875rem',
            },
            '& .MuiTablePagination-input': {
              display: 'block',
            },
          },
          '@media (max-width: 600px)': {
            '& .MuiDataGrid-root': {
              minWidth: '100%',
              // overflowX: 'auto',
            },
            '& .MuiDataGrid-cell': {
              fontSize: '12px',
              padding: '4px',
              whiteSpace: 'normal',
              wordBreak: 'break-word',
              borderBottom: '1px solid rgba(224, 224, 224, 1)',
            },
            '& .css-rtrcn9-MuiTablePagination-root .MuiTablePagination-selectLabel': {
              display: 'block',
            },
            '& .css-rtrcn9-MuiTablePagination-root .MuiTablePagination-input': {
              display: 'block',
            },
            '& .css-194a1fa-MuiSelect-select-MuiInputBase-input': {
              width: '50%',
            },
            '& .css-1cccqvr': {
              width: '50%',
            },
            '& .css-whi0l6 .MuiTablePagination-selectLabel': {
              display: 'block',
            },
            '& .css-whi0l6 .MuiTablePagination-input': {
              display: 'block',
            },
            '& .MuiTablePagination-input': {
              display: 'block',
            },
          },
          '& .makeStyles-caption-2': {
            display: 'none',
          },
          '@media (min-width:960px)': {
            '& .makeStyles-caption-2': {
              display: 'block',
            },
          },
        
          '& .MuiDataGrid-row': {
            '&:last-child': {
              '& .MuiDataGrid-cell': {
                borderBottom: 'none',
              },
            },
          },
        }}
        filterMode='server'
        sortingMode='server'
      />
      {loading && (
        <Box
          sx={{
            position: 'absolute',
            top: 0,
            left: isMobile ? 0 : 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(255, 255, 255, 0.8)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 1,
            transform: {
              xs: 'translateY(40px)',
              sm: 'translateY(48px)',
              md: 'translateY(56px)',
            },
          }}
        >
          <SkeletonLoader />
        </Box>
      )}
    </Box>
  );
};

export default DataGrids;