import React, { FC } from 'react';
import styled from '@emotion/styled';

export interface TitleProps {
  /** 标题 */
  title?: string;
  /** 副标题 */
  subtitle?: string;
  /** 标题后显示重要的非交互式状态信息 */
  titleMetadata?: React.ReactNode;
  /** 图片 */
  thumbnail?: React.ReactNode;
  /** 面包屑 */
  breadcrumb?: React.ReactNode;
}

const WrappedTitleMarkup = styled.div``;

const StyledTitle = styled.div<{ hasThumbnail: boolean }>`
  ${({ hasThumbnail }) =>
    hasThumbnail &&
    `
      display: grid;
      grid-gap: 16px;
      grid-template-columns: auto 1fr;

      ${WrappedTitleMarkup} {
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
    `}
`;

const TitleMarkup = styled.h1`
  margin: 0;
  font-weight: 600;
  font-size: 24px;
  color: #434343;

  word-break: break-word;
  overflow-wrap: break-word;

  @media (min-width: 640px) {
    font-size: 20px;
  }
`;

const TitleMetadata = styled.div`
  margin-top: 0;
  vertical-align: bottom;
`;

const SubTitle = styled.div`
  margin-top: 8px;
  color: #6d7175;
`;

const TitleThumbnail = styled.div`
  margin-right: 16px;
`;

const TitleWithMetadataWrapper = styled.div`
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  row-gap: 5px;

  ${TitleMarkup} {
    display: inline;
    margin-right: 16px;

    > * {
      display: inline;
    }
  }
`;

const BreadcrumbWrapper = styled.div`
  padding: 0 16px;
  border-left: 1px solid #6c757d;
`;

export const Title: FC<TitleProps> = ({
  title,
  titleMetadata,
  subtitle,
  thumbnail,
  breadcrumb,
}) => {
  const BreadcrumbNode = breadcrumb ? <BreadcrumbWrapper>{breadcrumb}</BreadcrumbWrapper> : null;

  const thumbnailMarkup = thumbnail ? <TitleThumbnail>{thumbnail}</TitleThumbnail> : null;

  const titleMarkup = title ? <TitleMarkup>{title}</TitleMarkup> : null;

  const titleMetadataMarkup = titleMetadata ? <TitleMetadata>{titleMetadata}</TitleMetadata> : null;

  const wrappedTitleMarkup = (
    <TitleWithMetadataWrapper>
      {titleMarkup}
      {BreadcrumbNode}
      {titleMetadataMarkup}
    </TitleWithMetadataWrapper>
  );

  const subtitleMarkup = subtitle ? <SubTitle>{subtitle}</SubTitle> : null;

  return (
    <StyledTitle hasThumbnail={!!thumbnail}>
      {thumbnailMarkup}
      <WrappedTitleMarkup>
        {wrappedTitleMarkup}
        {subtitleMarkup}
      </WrappedTitleMarkup>
    </StyledTitle>
  );
};
