import type { FC } from 'react';

import CardUI from '@material-hu/mui/Card';
import CardContent from '@material-hu/mui/CardContent';
import CardMedia from '@material-hu/mui/CardMedia';
import { Theme, useTheme, styled } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { DOMAIN_NAME_REGEX } from 'src/constants/posts';
import { LinkPreviewResponse } from 'src/types/previewLink';
import { getMetadata } from 'src/utils/previewLink';

const Card = styled(CardUI, {
  shouldForwardProp: prop => prop !== 'theme',
})(({ theme }: { theme: Theme }) => ({
  '& span': {
    fontFamily: theme.typography.fontFamily,
    color: '#646464',
    lineHeight: 1.2,
    marginTop: '8px',
    wordBreak: 'break-all',
  },
  '& h3': {
    fontFamily: theme.typography.fontFamily,
    fontSize: '1.17em',
    fontWeight: 'bold',
    color: 'black',
    marginTop: '8px',
    wordBreak: 'break-all',
  },
}));

export type PostPreviewLinkProps = {
  linkPreviews: Record<string, LinkPreviewResponse>;
};

export const PostPreviewLink: FC<PostPreviewLinkProps> = props => {
  const { linkPreviews = {} } = props;
  const theme = useTheme();

  const metadata = getMetadata(linkPreviews);
  const shortenedDomainName = metadata?.domainName?.replace(
    DOMAIN_NAME_REGEX,
    '$1',
  );

  if (!metadata) return null;

  return (
    <Card
      sx={{
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
        height: 'fit-content',
        borderRadius: '7px',
        backgroundColor: '#eef3f8',
        border: '1px solid #ccc',
        boxShadow: 'none',
      }}
      theme={theme}
    >
      {!!metadata?.image && (
        <CardMedia
          component="img"
          sx={{
            width: '100%',
            height: 'auto',
            maxHeight: '400px',
            objectFit: 'contain',
          }}
          image={metadata.image}
          alt=""
        />
      )}
      <CardContent
        sx={{
          pt: 1,
          pb: '10px !important',
          px: 1.5,
          display: 'flex',
          flexDirection: 'column',
          backgroundColor: 'white',
          width: '100%',
        }}
      >
        <Typography component="span">{shortenedDomainName}</Typography>
        <Typography variant="h3">{metadata?.title}</Typography>
      </CardContent>
    </Card>
  );
};

export default PostPreviewLink;
