import { Fragment, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';

import CardContainer from '@design-system/CardContainer';
import ListItem from '@design-system/List/components/ListItem';
import useDimensions from '@hooks/useDimensions';
import Divider from '@mui/material/Divider';
import Grid from '@mui/material/Grid';
import Stack from '@mui/material/Stack';
import { IconEdit } from '@tabler/icons-react';

import { getProfileDataContainerColumns } from './utils';

type DataContainerProps = {
  title: string;
  sections: ReactNode[];
  onEdit?: () => void;
  footer?: ReactNode;
};

const DataContainer = ({
  title,
  sections,
  onEdit,
  footer,
}: DataContainerProps) => {
  const { t } = useTranslation();
  const { ref, dimensions } = useDimensions();
  const { ref: firstSectionRef, dimensions: firstSectionDimensions } =
    useDimensions();

  const columns = getProfileDataContainerColumns(dimensions.width);

  if (sections.length === 0) {
    return null;
  }

  return (
    <CardContainer
      fullWidth
      ref={ref}
    >
      <ListItem
        text={{ title }}
        sx={{ '.MuiListItem-root': { p: 0, mb: 1 } }}
        {...(onEdit && {
          action: {
            Icon: IconEdit,
            onClick: onEdit,
            variant: 'secondary',
            'aria-label': `${t('general:edit')} ${title}`,
          },
        })}
      />
      <Grid
        container
        columns={columns}
        columnSpacing={2}
      >
        {sections.map((section, index) => {
          const isLastColumn = index % columns === columns - 1;
          const isLast = index === sections.length - 1;
          return (
            <Fragment key={index}>
              <Grid
                item
                xs={1}
              >
                <Stack
                  sx={{
                    '.MuiListItem-root': { p: 0 },
                    // titles of each section must never overflow the container
                    '& .MuiTypography-globalXXS': {
                      overflow: 'hidden',
                      whiteSpace: 'nowrap',
                      textOverflow: 'ellipsis',
                      maxWidth: firstSectionDimensions?.width - 1,
                    },
                  }}
                  ref={index === 0 ? firstSectionRef : null}
                >
                  {section}
                </Stack>
              </Grid>
              {isLastColumn && !isLast && (
                <Grid
                  item
                  xs={columns}
                >
                  <Divider sx={{ my: 1.5 }} />
                </Grid>
              )}
            </Fragment>
          );
        })}
      </Grid>
      {footer && <Stack sx={{ mt: 3 }}>{footer}</Stack>}
    </CardContainer>
  );
};

export default DataContainer;
