import React, { FC } from 'react';

import { LabelTag } from '@grafana/labels';
import { Stack, Button, Tooltip } from '@grafana/ui';
import { StackSize } from 'helpers/consts';

import { RenderConditionally } from 'components/RenderConditionally/RenderConditionally';
import { TooltipBadge } from 'components/TooltipBadge/TooltipBadge';
import { LabelKeyValue } from 'models/label/label.types';
import { components } from 'network/oncall-api/autogenerated-api.types';

interface LabelsTooltipBadgeProps {
  labels: LabelKeyValue[];
  onClick: (label: LabelKeyValue) => void;
}

export const LabelsTooltipBadge: FC<LabelsTooltipBadgeProps> = ({ labels, onClick }) =>
  labels.length ? (
    <TooltipBadge
      borderType="secondary"
      icon="tag-alt"
      addPadding
      text={labels?.length}
      tooltipContent={
        <Stack direction="column" gap={StackSize.sm}>
          {labels.map((label) => (
            <Stack gap={StackSize.sm} key={label.key.id}>
              <LabelTag label={label.key.name} value={label.value.name} />
              <Button
                size="sm"
                icon="filter"
                tooltip="Apply filter"
                variant="secondary"
                onClick={() => onClick(label)}
              />
            </Stack>
          ))}
        </Stack>
      }
    />
  ) : null;

interface LabelBadgesProps {
  labels: Array<components['schemas']['LabelPair']>;
  maxCount?: number;
}

export const LabelBadges: React.FC<LabelBadgesProps> = ({ labels = [], maxCount = 3 }) => {
  const renderer = (values: LabelBadgesProps['labels']) => {
    return (
      <Stack>
        {values.map((label) => (
          <LabelTag key={label.key.id} label={label.key.name} value={label.value.name} />
        ))}
      </Stack>
    );
  };

  return (
    <Stack gap={StackSize.sm}>
      {renderer(labels.slice(0, maxCount))}

      <RenderConditionally shouldRender={labels.length > maxCount}>
        <Tooltip content={renderer(labels.slice(maxCount))}>
          <div>{labels.length > maxCount ? `+ ${labels.length - maxCount}` : ``}</div>
        </Tooltip>
      </RenderConditionally>
    </Stack>
  );
};
