import React from 'react';
import type { TablePaginationProps, Theme } from '@mui/material';
import { paginationItemClasses, tablePaginationClasses } from '@mui/material';
import type { Components } from '@mui/material/styles';

import {
  fontSizeLarge,
  fontSizeMedium,
  fontSizeSmall,
  fontSizeXSmall,
  iconSizeLarge,
  iconSizeMedium,
  iconSizeSmall,
  iconSizeXSmall,
  largeSize,
  mediumSize,
  smallSize,
  xSmallSize,
} from '@/mui/components/constants';
import { SIZE_LARGE, SIZE_MEDIUM, SIZE_SMALL, SIZE_X_SMALL } from '@/mui/constants';

import Pagination from '@/mui/components/Pagination/Pagination';

type ActionsComponentProps = {
  className: string;
  count: number;
  rowsPerPage: number;
  page: number;
  onPageChange: () => void;
};

const fontSizes = {
  xSmall: fontSizeXSmall,
  small: fontSizeSmall,
  medium: fontSizeMedium,
  large: fontSizeLarge,
};

const sizes = {
  xSmall: xSmallSize,
  small: smallSize,
  medium: mediumSize,
  large: largeSize,
};

const iconFontSizes = {
  xSmall: iconSizeXSmall,
  small: iconSizeSmall,
  medium: iconSizeMedium,
  large: iconSizeLarge,
};

export default function MuiTablePagination(theme: Theme): Components['MuiTablePagination'] {
  return {
    defaultProps: {
      rowsPerPageOptions: [10, 20, 50],
      // @ts-expect-error todo: analize why this prop forbidden
      ActionsComponent: (props: ActionsComponentProps) => (
        <Pagination
          className={props.className}
          count={Math.ceil(props.count / props.rowsPerPage)}
          page={props.page + 1}
          onChange={props.onPageChange}
        />
      ),
    },
    styleOverrides: {
      root: {
        color: theme.palette.shades[900],
        flexShrink: 0,
      },
      select: {
        margin: 0,
      },
      selectIcon: {
        marginTop: 0,
      },
      selectLabel: {
        paddingRight: '20px',
      },
      actions: {
        marginLeft: '20px',
      },
      input: {
        width: 'initial',
        margin: '0 20px 0 0',
      },
    },
    variants: [
      ...[SIZE_X_SMALL, SIZE_SMALL, SIZE_MEDIUM, SIZE_LARGE].map((size$) => {
        const fontSize = fontSizes[size$ as keyof typeof fontSizes];
        const iconFontSize = iconFontSizes[size$ as keyof typeof iconFontSizes];
        const size = sizes[size$ as keyof typeof sizes];

        return {
          props: { size: size$ as TablePaginationProps['size'] },
          style: {
            [` .${tablePaginationClasses.selectIcon}`]: {
              fontSize: iconFontSize,
            },
            [` .${tablePaginationClasses.selectLabel}`]: {
              fontSize,
            },
            [` .${tablePaginationClasses.displayedRows}`]: {
              fontSize,
            },
            [` .${paginationItemClasses.root}`]: {
              fontSize,
              minWidth: size,
              height: size,
            },
          },
        };
      }),
    ],
  };
}
