import { type Key } from 'react';

import * as colors from '@material-hu/mui/colors';
import Stack, { type StackProps } from '@material-hu/mui/Stack';

const DisplayItem = ({ sx, ...other }: StackProps) => (
  <Stack
    sx={{
      border: '1px solid',
      borderColor: colors.grey[300],
      flex: 1,
      justifyContent: 'center',
      ...sx,
    }}
    {...other}
  />
);

type DataGroupProps<TData> = StackProps & {
  items: TData[];
  itemProps?: StackProps | ((item: TData) => StackProps);
  renderItem: (item: TData, index: number) => JSX.Element;
};

const DisplayGroup = <TData extends { id: Key }>({
  items,
  itemProps = {},
  renderItem,
  ...other
}: DataGroupProps<TData>) => (
  <Stack
    {...other}
    sx={{ flexDirection: 'row', width: '100%', ...other.sx }}
  >
    {items.map((item, index) => {
      const isFirstChild = index === 0;
      const isLastChild = index === items.length - 1;
      const nextItemProps =
        typeof itemProps === 'function' ? itemProps(item) : itemProps;

      return (
        <DisplayItem
          key={item.id}
          {...nextItemProps}
          sx={{
            ...(isFirstChild && {
              borderTopLeftRadius: '8px',
              borderBottomLeftRadius: '8px',
            }),
            ...(isLastChild && {
              borderTopRightRadius: '8px',
              borderBottomRightRadius: '8px',
              borderLeft: 'none',
            }),
            ...(!isFirstChild && !isLastChild && { borderLeft: 'none' }),
            padding: 1,
            ...nextItemProps.sx,
          }}
        >
          {renderItem(item, index)}
        </DisplayItem>
      );
    })}
  </Stack>
);

DisplayGroup.Item = DisplayItem;

export default DisplayGroup;
