// ReusableTable.jsx
import { useMemo } from 'react';
import {
  MaterialReactTable,
  useMaterialReactTable,
} from 'material-react-table';
import { Box } from '@mui/material';
import { ArrowDropUp, ArrowDropDown } from '@mui/icons-material';
import TableFooter from './TableFooter';

// Конфигурация стилей по умолчанию
const DEFAULT_TABLE_STYLES = {
  paper: {
    border: '1px solid #f2f2f2',
    padding: 0,
    boxShadow: 'none',
    overflow: 'hidden',
    position: 'relative',
  },
  container: {
    overflow: 'auto',
  },
  headRow: {
    position: 'sticky',
    backgroundColor: '#F9FAFB',
    color: '#4A5565',
    fontSize: '0.88rem',
  },
  headCell: {
    padding: '1rem 0.75rem',
    fontSize: 'inherit',
    fontWeight: 'bold',
  },
  bodyCell: {
    padding: '0.75rem',
    fontSize: '0.75rem',
    lineHeight: '150%',
    color: '#364153',
  },
  bodyRow: {
    '&:hover': {
      backgroundColor: 'white !important',
    },
    '&:hover td::after': {
      opacity: '0 !important',
      backgroundColor: 'transparent !important',
    },
    '&:hover .MuiTableCell-root': {
      backgroundColor: 'white !important',
    },
  },
};

// Иконки сортировки по умолчанию
const DEFAULT_SORT_ICONS = {
  ArrowUpwardIcon: (props) => <ArrowDropUp {...props} />,
  ArrowDownwardIcon: (props) => <ArrowDropDown {...props} />,
  SyncAltIcon: () => (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: 0,
        lineHeight: 0,
        marginBottom: '5px',
      }}
    >
      <ArrowDropUp sx={{ marginBottom: '-5px' }} />
      <ArrowDropDown sx={{ marginBottom: '-5px' }} />
    </div>
  ),
};

const StyledTable = ({
  columns,
  data,
  // Опции пагинации
  enablePagination = true,
  page = 0,
  rowsPerPage = 10,
  totalCount = 0,
  onPageChange,
  onRowsPerPageChange,
  rowsPerPageOptions = [10, 20, 50, 100],
  // Опции высоты
  containerHeight = 'calc(100vh - 450px)',
  minHeight = '400px',
  maxHeight,
  // Кастомные стили
  customStyles = {},
  // Дополнительные пропсы таблицы
  tableOptions = {},
  // Загрузка
  loading = false,
  // Действия со строками
  renderRowActions,
  enableRowActions = false,
  positionActionsColumn = 'last',
  // Сортировка
  enableSorting = false,
  // Фильтры
  enableColumnFilters = false,
  enableGlobalFilter = false,
  // Верхняя панель
  enableTopToolbar = false,
  // Начальное состояние
  initialState = {},
  // Кастомные иконки
  icons = DEFAULT_SORT_ICONS,
  // Футер
  customFooter, // Кастомный футер вместо стандартного
}) => {
  // Слияние стилей с кастомными
  const tableStyles = useMemo(() => {
    return {
      paper: { ...DEFAULT_TABLE_STYLES.paper, ...customStyles.paper },
      container: {
        ...DEFAULT_TABLE_STYLES.container,
        ...customStyles.container,
      },
      headRow: { ...DEFAULT_TABLE_STYLES.headRow, ...customStyles.headRow },
      headCell: { ...DEFAULT_TABLE_STYLES.headCell, ...customStyles.headCell },
      bodyCell: { ...DEFAULT_TABLE_STYLES.bodyCell, ...customStyles.bodyCell },
      bodyRow: { ...DEFAULT_TABLE_STYLES.bodyRow, ...customStyles.bodyRow },
    };
  }, [customStyles]);

  const containerSx = useMemo(() => {
    const heightStyles = {};
    if (maxHeight) {
      heightStyles.maxHeight = maxHeight;
    } else {
      heightStyles.maxHeight = containerHeight;
    }
    if (minHeight) {
      heightStyles.minHeight = minHeight;
    }
    return {
      ...tableStyles.container,
      ...heightStyles,
    };
  }, [containerHeight, minHeight, maxHeight, tableStyles.container]);

  const hasFooter = useMemo(() => {
    if (customFooter) return true;
    if (
      enablePagination &&
      onPageChange &&
      onRowsPerPageChange &&
      totalCount > 0
    ) {
      return true;
    }
    return false;
  }, [
    customFooter,
    enablePagination,
    onPageChange,
    onRowsPerPageChange,
    totalCount,
  ]);

  const paperBorderRadius = useMemo(() => {
    if (hasFooter) {
      return '.63rem .63rem 0 0';
    } else {
      return '.63rem';
    }
  }, [hasFooter]);

  const table = useMaterialReactTable({
    columns,
    data,
    enableEditing: false,
    enableRowActions,
    positionActionsColumn,
    icons,
    initialState: {
      ...initialState,
    },
    displayColumnDefOptions: tableOptions.displayColumnDefOptions || {},
    enableTopToolbar,
    renderRowActions: renderRowActions || (() => null),
    enableColumnFilters,
    enableGlobalFilter,
    enableSorting,
    enablePagination: false,
    manualPagination: enablePagination,
    rowCount: totalCount,
    state: {
      isLoading: loading,
    },
    localization: {
      noRecordsToDisplay: 'Нет данных для отображения',
      ...tableOptions.localization,
    },
    muiTablePaperProps: {
      sx: {
        ...tableStyles.paper,
        borderRadius: paperBorderRadius,
      },
    },
    muiTableContainerProps: {
      sx: containerSx,
    },
    muiTableBodyRowProps: {
      sx: tableStyles.bodyRow,
    },
    muiTableHeadProps: {
      sx: {
        position: 'sticky',
        top: 0,
        zIndex: 10,
      },
    },
    muiTableHeadRowProps: {
      sx: tableStyles.headRow,
    },
    muiTableBodyCellProps: {
      sx: tableStyles.bodyCell,
    },
    muiTableHeadCellProps: {
      sx: tableStyles.headCell,
    },
    muiBottomToolbarProps: {
      sx: {
        display: 'none',
      },
    },
    ...tableOptions,
  });

  // Рендер футера
  const renderFooter = () => {
    if (customFooter) {
      return customFooter;
    }

    if (
      enablePagination &&
      onPageChange &&
      onRowsPerPageChange &&
      totalCount > 0
    ) {
      return (
        <TableFooter
          totalCount={totalCount}
          page={page}
          rowsPerPage={rowsPerPage}
          onPageChange={onPageChange}
          onRowsPerPageChange={onRowsPerPageChange}
          rowsPerPageOptions={rowsPerPageOptions}
        />
      );
    }

    return null;
  };

  return (
    <Box sx={{ position: 'relative' }}>
      <MaterialReactTable table={table} />
      {renderFooter()}
    </Box>
  );
};

export default StyledTable;
