import * as React from 'react';
import clsx from 'clsx';

type KeyValueTableDerivedElement = HTMLDListElement;

interface KeyValueProperty {
  key: string;
  className?: string;
  valueProps?: React.HTMLProps<HTMLElement>;
}

export interface KeyValueTableProps extends Omit<React.HTMLProps<KeyValueTableDerivedElement>, 'children'> {
  hiddenKeys?: boolean;
  properties?: (KeyValueProperty | boolean)[];
}

export const KeyValueTable = React.forwardRef<KeyValueTableDerivedElement, KeyValueTableProps>(({
  hiddenKeys = false,
  properties = [],
  ...etcProps
}, forwardedRef) => (
  <dl
    {...etcProps}
    className={clsx(
      'grid gap-y-1 grid-cols-3',
    )}
    ref={forwardedRef}
  >
    {
      properties.map((property) => typeof property === 'object' && (
        <div
          key={property.key}
          className={clsx('contents', property.className)}
        >
          <dt
            className={clsx(hiddenKeys && 'sr-only', 'pr-4')}
          >
            {property.key}
          </dt>
          <dd
            {...(property.valueProps ?? {})}
            className={clsx(
              'm-0 text-ellipsis overflow-hidden',
              !hiddenKeys && 'col-span-2',
              hiddenKeys && 'col-span-3',
              property.valueProps?.className,
            )}
          >
            {property.valueProps?.children}
          </dd>
        </div>
      ))
    }
  </dl>
));

KeyValueTable.displayName = 'KeyValueTable';
