import { DescriptionsItem, DescriptionsItemProps } from './items/DescriptionsItem';

export type DescriotionItemType = {
  items: (DescriptionsItemProps & { key?: string })[];
  column?: 1 | 2 | 3 | 4;
  titleWidth?: number;
  className?: string;
  titleClassName?: string;
  contentClassName?: string;
};

export const Descriptions = (props: DescriotionItemType) => {
  const { items, column = 1, titleWidth, className, titleClassName, contentClassName } = props;

  const columnClassName =
    {
      1: 'grid-cols-1',
      2: 'grid-cols-2',
      3: 'grid-cols-3',
      4: 'grid-cols-4',
    }[column] || 'grid-cols-1';

  const getFirstRowItemIndices = () => {
    const firstRowItemIndices: number[] = [];
    let availableColumns = column;

    for (let index = 0; index < items.length; index += 1) {
      if (availableColumns <= 0) {
        break;
      }

      const item = items[index];
      const itemSpan = item.span === 'filled' ? column : (item.span ?? 1);
      const effectiveSpan = Math.min(typeof itemSpan === 'number' ? itemSpan : column, column);

      if (effectiveSpan > availableColumns) {
        break;
      }

      firstRowItemIndices.push(index);
      availableColumns -= effectiveSpan;

      if (availableColumns === 0) {
        break;
      }
    }

    return firstRowItemIndices;
  };

  const firstRowItemIndices = getFirstRowItemIndices();

  return (
    <div className={`grid w-full gap-0 ${columnClassName || ''} ${className || ''}`}>
      {items.map((item, index) => {
        const { key, ...itemProps } = item;
        return (
          <DescriptionsItem
            key={key || index}
            {...itemProps}
            isFirstRow={firstRowItemIndices.includes(index)}
            titleWidth={titleWidth}
            titleClassName={titleClassName}
            contentClassName={contentClassName}
          />
        );
      })}
    </div>
  );
};
