import { ReactNode } from 'react';

import Stack from '@material-hu/mui/Stack';

import TableLoader, {
  TableLoaderProps,
} from '@material-hu/components/design-system/Table/components/TableLoader';
import Title from '@material-hu/components/design-system/Title';

import { PAGE_SIZE } from '../../constants';
import { JourneyListItemProps } from '../../types';

import { ListEmpty } from './ListEmpty';
import { ListItem } from './ListItem';
import { ListLoading } from './ListLoading';

type ItemsListProps = {
  title: string;
  description?: string;
  items: JourneyListItemProps[];
  isLoading: boolean;
  hideIfEmpty?: boolean;
  skeletonsLength?: number;
  headerRight?: ReactNode;
  pagination?: TableLoaderProps;
  emptyTexts?: {
    title: string;
    description: string;
  };
};

const ItemsList = ({
  title,
  description,
  items,
  isLoading,
  emptyTexts,
  skeletonsLength = 3,
  hideIfEmpty = false,
  headerRight,
  pagination,
}: ItemsListProps) => {
  const isEmpty = !isLoading && !items.length;

  if (isEmpty && hideIfEmpty) return null;

  return (
    <Stack
      sx={{ gap: 2 }}
      key={title}
    >
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <Title
          variant="M"
          title={title}
          description={description}
        />
        {headerRight}
      </Stack>
      {isLoading && <ListLoading skeletonsLength={skeletonsLength} />}
      {isEmpty && emptyTexts && <ListEmpty emptyTexts={emptyTexts} />}
      {!isLoading &&
        items.map((item, index) => (
          <ListItem
            key={item.id}
            item={item}
            index={index}
          />
        ))}
      {pagination && pagination.totalCount! > PAGE_SIZE && (
        <TableLoader {...pagination} />
      )}
    </Stack>
  );
};

export default ItemsList;
