import { clsx } from 'clsx';

import ActionButton from '../actionButton';
import { Layout } from '../common';

export interface DefinitionListDefinition {
  action?: {
    label: string;
    onClick?: React.MouseEventHandler<HTMLButtonElement>;
  };
  title: React.ReactNode;
  value: React.ReactNode;
  key: string;
}

type DefinitionListLayout =
  `${Layout.VERTICAL_TWO_COLUMN | Layout.VERTICAL_ONE_COLUMN | Layout.HORIZONTAL_JUSTIFIED | Layout.HORIZONTAL_LEFT_ALIGNED | Layout.HORIZONTAL_RIGHT_ALIGNED}`;

export interface DefinitionListProps {
  definitions?: DefinitionListDefinition[];
  layout?: DefinitionListLayout;
  muted?: boolean;
}

const isLayoutHorizontal = (layout: DefinitionListLayout) =>
  layout === Layout.HORIZONTAL_LEFT_ALIGNED ||
  layout === Layout.HORIZONTAL_RIGHT_ALIGNED ||
  layout === Layout.HORIZONTAL_JUSTIFIED;

const getAlignmentClasses = (
  layout: DefinitionListLayout,
  action: DefinitionListDefinition['action'],
) => {
  const classes = ['d-flex'];

  if (action) {
    if (isLayoutHorizontal(layout)) {
      classes.push('align-items-center');
    } else {
      classes.push('align-items-start');
    }
  }

  if (layout === Layout.HORIZONTAL_RIGHT_ALIGNED) {
    classes.push('text-sm-right tw-definition-list--right-aligned-desktop');
  } else {
    classes.push('justify-content-between');
  }

  if (layout === Layout.HORIZONTAL_JUSTIFIED) {
    classes.push('text-sm-justify');
  }

  return classes;
};

const defaultDefinitions = [] satisfies DefinitionListProps['definitions'];

export default function DefinitionList({
  definitions = defaultDefinitions,
  layout = 'VERTICAL_TWO_COLUMN',
  muted,
}: DefinitionListProps) {
  return (
    <dl
      className={clsx('tw-definition-list d-flex ', {
        'text-muted': muted,
        'flex-column': layout === Layout.VERTICAL_ONE_COLUMN,
        'tw-definition-list--columns flex-column flex-row--sm':
          layout === Layout.VERTICAL_TWO_COLUMN,
        'tw-definition-list--horizontal flex-column': isLayoutHorizontal(layout),
      })}
    >
      {definitions
        .filter((definition) => definition)
        .map(({ action, title, value, key }) => (
          <div key={key} className="tw-definition-list__item">
            <dt>{title}</dt>
            <dd className={clsx(...getAlignmentClasses(layout, action))}>
              <div>{value}</div>
              {action ? (
                <div
                  className={clsx(
                    isLayoutHorizontal(layout) ? 'p-l-2' : 'p-x-2',
                    'tw-definition-list__action',
                  )}
                >
                  <ActionButton className="tw-definition-list__button" onClick={action.onClick}>
                    {action.label}
                  </ActionButton>
                </div>
              ) : null}
            </dd>
          </div>
        ))}
    </dl>
  );
}
