import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';

import { RecentlyViewedIcon } from '@redocly/theme/icons/RecentlyViewedIcon/RecentlyViewedIcon';
import { CheckmarkOutlineIcon } from '@redocly/theme/icons/CheckmarkOutlineIcon/CheckmarkOutlineIcon';
import { useThemeHooks } from '@redocly/theme/core/hooks';
import { VERSION_NOT_SPECIFIED } from '@redocly/theme/core/constants';
import { Tooltip } from '@redocly/theme/components/Tooltip/Tooltip';
import { useIsTruncated } from '@redocly/theme/core/hooks';

export type CatalogHistoryButtonProps = {
  version: string | null;
  className?: string;
};

export function CatalogEntityHistoryButton({
  version,
  className,
}: CatalogHistoryButtonProps): React.ReactElement {
  const [label, setLabel] = useState(version === VERSION_NOT_SPECIFIED ? null : version);
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();
  const [labelRef, isLabelTruncated] = useIsTruncated<HTMLSpanElement>(label);

  const handleClose = useCallback(
    (e: CustomEvent): void => {
      setLabel(
        e.detail.version === VERSION_NOT_SPECIFIED
          ? e.detail.revision || 'r.1'
          : `${e.detail.version || version}, ${e.detail.revision || 'r.1'}`,
      );
    },
    [version],
  );

  useEffect(() => {
    window.addEventListener('portal:sidebar:close-version-history', (e) =>
      handleClose(e as CustomEvent),
    );

    return () => {
      window.removeEventListener('portal:sidebar:close-version-history', (e) =>
        handleClose(e as CustomEvent),
      );
    };
  }, [handleClose]);

  const handleClick = (): void => {
    window.dispatchEvent(new CustomEvent('portal:sidebar:open-version-history'));
  };

  return (
    <CatalogHistoryButtonWrapper
      className={className}
      data-component-name="Catalog/CatalogHistoryButton"
    >
      <Separator />
      <HistoryItem onClick={handleClick}>
        <HistoryIcon />
        <HistoryContent>
          <HistoryText>{translate('catalog.history.button.label', 'Version history')}</HistoryText>
          {label && (
            <Tooltip
              tip={label}
              placement="bottom"
              arrowPosition="left"
              disabled={!isLabelTruncated}
            >
              <VersionPillWrapper>
                <VersionPill>
                  <CheckmarkIcon />
                  <span ref={labelRef}>{label}</span>
                </VersionPill>
              </VersionPillWrapper>
            </Tooltip>
          )}
        </HistoryContent>
      </HistoryItem>
    </CatalogHistoryButtonWrapper>
  );
}

const CatalogHistoryButtonWrapper = styled.div`
  width: var(--catalog-history-button-width);
`;

const Separator = styled.div`
  width: 100%;
  height: 1px;
  background-color: var(--catalog-history-separator-border-color);
  margin-bottom: var(--catalog-history-separator-margin-bottom);
  flex-shrink: 0;
`;

const HistoryItem = styled.button`
  all: unset;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--catalog-history-item-gap);
  padding: var(--catalog-history-item-padding);
  margin-bottom: var(--catalog-history-item-margin-bottom);
  width: var(--catalog-history-button-item-width);
  border-radius: var(--catalog-history-item-border-radius);
  cursor: pointer;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: var(--catalog-history-item-bg-color-hover);
  }
`;

const HistoryContent = styled.div`
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  flex: 1;
  gap: var(--catalog-history-item-gap);
  min-width: 0;
  max-width: var(--catalog-history-content-max-width);
`;

const HistoryText = styled.span`
  flex: 0 0 auto;
  font-family: var(--catalog-history-text-font-family);
  font-size: var(--catalog-history-text-font-size);
  font-weight: var(--catalog-history-text-font-weight);
  line-height: var(--catalog-history-text-line-height);
  color: var(--catalog-history-text-color);
  white-space: nowrap;
`;

const VersionPillWrapper = styled.div`
  flex: 0 1 auto;
  min-width: 0;
  max-width: var(--catalog-history-content-max-width);
`;

const HistoryIcon = styled(RecentlyViewedIcon)`
  width: var(--catalog-history-icon-size);
  height: var(--catalog-history-icon-size);
  flex-shrink: 0;
`;

const VersionPill = styled.div`
  display: flex;
  align-items: center;
  gap: var(--catalog-history-pill-gap);
  padding: var(--catalog-history-pill-padding-vertical) var(--catalog-history-pill-padding-horizontal);
  border: 1px solid var(--catalog-history-pill-border-color);
  border-radius: var(--catalog-history-pill-border-radius);
  background-color: transparent;
  min-width: 0;
  max-width: 100%;

  span {
    font-family: var(--catalog-history-pill-font-family);
    font-size: var(--catalog-history-pill-font-size);
    line-height: var(--catalog-history-pill-line-height);
    color: var(--catalog-history-pill-text-color);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    min-width: 0;
  }
`;

const CheckmarkIcon = styled(CheckmarkOutlineIcon)`
  width: var(--catalog-history-pill-icon-size);
  height: var(--catalog-history-pill-icon-size);
  min-width: var(--catalog-history-pill-icon-size);
  min-height: var(--catalog-history-pill-icon-size);
  flex-shrink: 0;
  color: var(--catalog-history-pill-icon-color);
`;
