import React, { useState } from "react";

import {
  Stack,
  TableBody,
  TableFooter,
  TablePagination,
  TableRow,
  Typography,
} from "@mui/material";
import TablePaginationActions from "@mui/material/TablePagination/TablePaginationActions";

import { Table } from "../../../components/Table";
import { TableCell } from "../../../components/Table/TableCell";
import TableHead from "../../../components/Table/TableHead";
import TableHeading from "../../../components/Table/TableHeading";
import { useI18n } from "../../../contexts/I18nContext";
import { SubscriptionPeriod } from "../types/subscription";

import SubscriptionsListItem from "./SubscriptionsListItem";

export interface SubscriptionsListProps {
  periods: SubscriptionPeriod[] | null;
  refresh: () => void;
}

export const SubscriptionsList: React.FC<SubscriptionsListProps> = ({ periods }) => {
  const { t } = useI18n();
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(3);

  // Avoid a layout jump when reaching the last page with empty rows.
  const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - (periods?.length ?? 0)) : 0;

  const handleChangePage = (_: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    setRowsPerPage(Number.parseInt(event.target.value, 10));
    setPage(0);
  };

  if (periods == null || periods?.length === 0) return null;

  return (
    <>
      <Stack px={3} py={2}>
        <Typography fontWeight={700} variant="body1">
          {t("Payments")}
        </Typography>
      </Stack>

      <Table count={periods?.length ?? 0}>
        <TableHead>
          <TableHeading width={150}>{t("Payment date")}</TableHeading>
          <TableHeading>{t("Due date")}</TableHeading>
          <TableHeading align="right">{t("Amount")}</TableHeading>
          <TableHeading align="right">{t("#")}</TableHeading>
          <TableHeading align="right">{t("Status")}</TableHeading>
          <TableHeading />
        </TableHead>

        <TableBody>
          {periods &&
            (rowsPerPage > 0
              ? periods.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
              : periods
            ).map((row) => <SubscriptionsListItem key={row.id} period={row} />)}

          {emptyRows > 0 && (
            <TableRow style={{ height: 53 * emptyRows }}>
              <TableCell colSpan={6} />
            </TableRow>
          )}
        </TableBody>

        <TableFooter>
          <TableRow>
            <TablePagination
              ActionsComponent={TablePaginationActions}
              colSpan={6}
              count={periods?.length ?? 0}
              page={page}
              rowsPerPage={rowsPerPage}
              rowsPerPageOptions={[3, 6, 12, { label: "All", value: -1 }]}
              slotProps={{
                select: {
                  inputProps: { "aria-label": "rows per page" },
                  native: true,
                },
              }}
              sx={{ "& .MuiTablePagination-toolbar": { pr: 1.5 } }}
              onPageChange={handleChangePage}
              onRowsPerPageChange={handleChangeRowsPerPage}
            />
          </TableRow>
        </TableFooter>
      </Table>
    </>
  );
};

export default SubscriptionsList;
