import React from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';

import { useThemeHooks } from '@redocly/theme/core/hooks';
import { getScorecardColorVariable } from '@redocly/theme/core/utils';
import { Tag } from '@redocly/theme/components/Tag/Tag';
import { Link } from '@redocly/theme/components/Link/Link';

export type CatalogClassicInfoBlockProps = {
  metadata?: {
    scorecardLevel?: string;
    scoreCardSlug?: string;
    scorecardLevelIdx?: number;
    /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
    scorecardLevels?: Record<string, any>;

    [key: string]: unknown;
  };
};

export function CatalogClassicInfoBlock(props: CatalogClassicInfoBlockProps): JSX.Element {
  const scorecardBadge = props.metadata?.scorecardLevel ? (
    <ScorecardBadge
      level={props.metadata.scorecardLevel as string}
      slug={props.metadata?.scoreCardSlug as string}
      colorVariable={getScorecardColorVariable(
        props.metadata?.scorecardLevelIdx || 0,
        Object.keys(props.metadata?.scorecardLevels || {}).length,
      )}
    />
  ) : null;

  return (
    <CatalogInfoBlockWrapper>
      <CatalogBadgesWrapper data-component-name="CatalogClassic/CatalogClassicInfoBlock">
        {scorecardBadge}
      </CatalogBadgesWrapper>
    </CatalogInfoBlockWrapper>
  );
}

function ScorecardBadge(props: {
  level: string;
  slug: string;
  colorVariable: string;
}): JSX.Element {
  const { level, slug, colorVariable } = props;
  const { useTelemetry } = useThemeHooks();
  const telemetry = useTelemetry();
  return (
    <Link to={slug}>
      <Tag
        onClick={() =>
          telemetry.sendScorecardLinkClickedMessage([{ object: 'link', action: 'click' }])
        }
        withStatusDot
        statusDotColor={`var(${colorVariable})`}
      >
        {level}
      </Tag>
    </Link>
  );
}

const CatalogInfoBlockWrapper = styled.div`
  position: relative;
  width: 100%;
`;

const CatalogBadgesWrapper = styled.div`
  &:empty {
    display: none;
  }

  position: absolute;
  z-index: 10;
  right: 0;
  margin-top: var(--panel-gap-vertical);

  --badge-border-radius: var(--catalog-classic-page-badge-border-radius);
  --badge-padding: var(--catalog-classic-page-badge-padding);
  --badge-font-size: var(--catalog-classic-page-badge-font-size);
  --badge-line-height: var(--catalog-classic-page-badge-line-height);
  --badge-dot-size: var(--catalog-classic-page-badge-dot-size);
  --badge-dot-border-color: var(--catalog-classic-page-badge-dot-border-color);
`;
