import React from 'react';
import styled, { css } from 'styled-components';

import type { JSX } from 'react';

import { Link } from '@redocly/theme/components/Link/Link';
import { Tooltip } from '@redocly/theme/components/Tooltip/Tooltip';
import { BreadcrumbIcon } from '@redocly/theme/components/Breadcrumbs/BreadcrumbIcon';
import { trimText } from '@redocly/theme/core/utils';
import { BREADCRUMB_MAX_LENGTH } from '@redocly/theme/core/constants';

type BreadcrumbProps = {
  label: string;
  link?: string;
  isActive: boolean;
  onClick?: () => void;
  icon?: string;
};

export function Breadcrumb({ label, link, isActive, onClick, icon }: BreadcrumbProps): JSX.Element {
  const isTruncated = label.length > BREADCRUMB_MAX_LENGTH;
  const displayLabel = trimText(label, BREADCRUMB_MAX_LENGTH);
  const content = (
    <>
      <BreadcrumbIcon icon={icon} />
      {displayLabel}
    </>
  );

  const breadcrumbContent = link ? (
    <BreadcrumbLink
      data-component-name="Breadcrumbs/BreadcrumbLink"
      to={link}
      onClick={onClick}
      $isActive={isActive}
    >
      {content}
    </BreadcrumbLink>
  ) : (
    <BreadcrumbWrapper
      data-component-name="Breadcrumbs/BreadcrumbWrapper"
      $isActive={isActive}
      onClick={onClick}
      tabIndex={-1}
    >
      {content}
    </BreadcrumbWrapper>
  );

  return isTruncated ? (
    <Tooltip tip={label} placement="bottom">
      {breadcrumbContent}
    </Tooltip>
  ) : (
    breadcrumbContent
  );
}

const baseBreadcrumbStyles = `
  display: flex;
  align-items: center;
  gap: var(--breadcrumbs-gap);
  padding: var(--breadcrumb-padding);
  border-radius: var(--border-radius);
  color: var(--breadcrumbs-text-color);
  text-decoration: none;

  &:hover {
    background-color: var(--breadcrumbs-background-color-hover);
  }

  &:focus {
    box-shadow: var(--breadcrumbs-box-shadow-focus);
    outline: none;
  }
`;

const activeColorStyles = css`
  color: var(--breadcrumbs-text-color-active);
`;

const BreadcrumbWrapper = styled.div<{ $isActive: boolean }>`
  ${baseBreadcrumbStyles}

  ${(props) => props.$isActive && activeColorStyles}
  cursor: default;
  pointer-events: none;

  &:focus {
    box-shadow: none;
    outline: none;
  }

  &:hover {
    background-color: transparent;
  }
`;

const BreadcrumbLink = styled(Link)<{ $isActive: boolean }>`
  ${baseBreadcrumbStyles}
  ${(props) => props.$isActive && activeColorStyles}
`;
