import { Children, isValidElement, useEffect, useMemo } from 'react';

import { type UniqueIdentifier } from '@dnd-kit/core';
import {
  horizontalListSortingStrategy,
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { Stack } from '@mui/material';

import { useSortableListContext } from '../../context';
import { type ContainerProps } from '../../types';

const Container = ({ id, children, overlay, sx = {} }: ContainerProps) => {
  const context = useSortableListContext();
  const { direction, registerContainer, unregisterContainer } = context;

  const childIds = useMemo(() => {
    const ids: UniqueIdentifier[] = [];
    Children.forEach(children, child => {
      if (isValidElement(child) && child.props && 'id' in child.props) {
        ids.push(child.props.id);
      }
    });
    return ids;
  }, [children]);

  useEffect(() => {
    registerContainer(id, childIds);
    return () => {
      unregisterContainer(id);
    };
  }, [id, childIds, registerContainer, unregisterContainer]);

  return (
    <SortableContext
      id={id}
      items={childIds}
      strategy={
        direction === 'vertical'
          ? verticalListSortingStrategy
          : horizontalListSortingStrategy
      }
    >
      <Stack
        component="ul"
        sx={{
          listStyle: 'none',
          listStyleType: 'none',
          appearance: 'none',
          padding: 0,
          margin: 0,
          ...(direction === 'vertical'
            ? { flexDirection: 'column' }
            : { flexDirection: 'row' }),
          ...sx,
        }}
      >
        {children}
      </Stack>
      {overlay}
    </SortableContext>
  );
};

Container.displayName = 'SortableList.Container';

export default Container;
