import type { OnChangeFn, PaginationState } from "@edr/ui-common";
import { Group, Pagination, Select, Text } from "@mantine/core";

export interface RuleEngineListFooterProps {
  pagination: PaginationState;
  pageCount: number;
  totalCount: number;
  itemLabel: string;
  onPaginationChange: OnChangeFn<PaginationState>;
}

const PAGE_SIZE_OPTIONS = ["5", "10", "25", "50"];

const RuleEngineListFooter = ({
  pagination,
  pageCount,
  totalCount,
  itemLabel,
  onPaginationChange,
}: RuleEngineListFooterProps) => {
  const { pageIndex, pageSize } = pagination;
  const start = totalCount === 0 ? 0 : pageIndex * pageSize + 1;
  const end = Math.min((pageIndex + 1) * pageSize, totalCount);

  const setPageIndex = (nextIndex: number) => {
    onPaginationChange({ pageIndex: nextIndex, pageSize });
  };

  const setPageSize = (nextSize: number) => {
    onPaginationChange({ pageIndex: 0, pageSize: nextSize });
  };

  return (
    <Group
      justify="space-between"
      align="center"
      wrap="wrap"
      p="md"
      style={{ borderTop: "1px solid var(--mantine-color-gray-2)" }}
    >
      <Group gap="md" align="center">
        <Group gap="xs" align="center">
          <Text size="sm" c="dimmed">
            Rows per page
          </Text>
          <Select
            value={String(pageSize)}
            onChange={(value) => value && setPageSize(Number(value))}
            data={PAGE_SIZE_OPTIONS}
            size="xs"
            w={70}
            allowDeselect={false}
          />
        </Group>
        <Text size="sm" c="dimmed">
          Showing {start}–{end} of {totalCount} {itemLabel}
        </Text>
      </Group>

      {pageCount > 1 && (
        <Pagination
          value={pageIndex + 1}
          total={pageCount}
          size="sm"
          radius="md"
          onChange={(page) => setPageIndex(page - 1)}
        />
      )}
    </Group>
  );
};

export default RuleEngineListFooter;
