import React from 'react';
import { Box, Text, TextButton } from '@wix/design-system';
import {
  useCollectionPageContext,
  useWixPatternsContainer,
} from '@wix/bex-core/react';
import { useSelector } from '../../useSelector';
import { withoutDefaults } from '@wix/bex-core';
import { cairoPageCtaClicked } from '@wix/bex-core/bi';
import { useIsMobile } from '../../hooks/useIsMobile';

/**
 * Props for the PageSubTitle component.
 * @property {string} text The subtitle text.
 * @property {Object} [learnMore] An object with a `url` (required) for displaying a link button on the subtitle.
 * @property {string} learnMore.url where the link should navigate to
 * @property {string} [learnMore.label ="Learn more"] - the label of the link button. defaults to "Learn More"
 */
export interface PageSubTitleProps {
  text: string;
  learnMore?: {
    url: string;
    label?: string;
  };
}

/**
 * Renders a page subtitle with an optional learn more button
 * @component
 * @param {PageSubTitleProps} props The props for the component.
 * @example
 * ```jsx
 * <PageSubTitle text="Welcome to my page" learnMore={{ url: "/learn-more", label: "Learn More" }} />
 * ```
 */
export const PageSubTitle = ({ text, learnMore }: PageSubTitleProps) => {
  const { translate: t, initTask } = useWixPatternsContainer();
  const { bi } = useCollectionPageContext();
  useSelector(() => initTask.status);

  const isMobile = useIsMobile();

  const learnMoreSuffix = learnMore ? (
    <TextButton
      dataHook="subtitle-learn-more-cta"
      as="a"
      rel="noopener"
      target="_blank"
      href={learnMore.url}
      size={isMobile ? 'small' : 'medium'}
      style={{ marginLeft: '6px' }}
      onClick={() => {
        bi?.reportBI(
          withoutDefaults(cairoPageCtaClicked)({
            location: 'Collection Page Header',
            ctaType: 'link',
            ctaName: 'Learn more',
          }),
        );
      }}
    >
      {learnMore.label ?? t('cairo.subtitle.learnMore')}
    </TextButton>
  ) : undefined;

  return (
    <Box
      dataHook="page-subtitle"
      width="100%"
      minWidth={0}
      verticalAlign="bottom"
    >
      <Text
        ellipsis
        secondary
        maxLines={2}
        suffix={learnMoreSuffix}
        tooltipProps={{
          placement: 'auto',
        }}
      >
        {text}
      </Text>
    </Box>
  );
};
