import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { Text } from "@bufferapp/components";
import MediaIcon from "../../MediaIcon";
import ReactPlayer from "react-player";

const Container = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
`;

const Media = styled.div`
  width: 100%;
  height: 100%;
  background: transparent;
  background-image: url(${(props) => props.thumbnail});
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
`;

const Empty = styled.div`
  width: 100%;
  height: 100%;
  background: #fdfdfd;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: inset 0 0 8px rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
`;

const TypeIcon = styled.div`
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.75);
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.08);
  position: absolute;
  right: 10px;
  bottom: 10px;
  border-radius: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const MediaContainer = styled.div`
  position: relative;
  width: 100%;
  height: 100%;
`;

const Attachment = ({ type, media }) => {
  function getThumbnail() {
    if (type === "video") {
      return (
        <MediaContainer>
          {String(media.thumbnail).match(/\.mp4/) && (
            <ReactPlayer
              url={media.thumbnail}
              width="200%"
              height="200%"
              mute
              style={{
                display: "flex",
                background: "#F5F5F5",
                width: "200%",
                height: "200%",
                position: "relative",
                top: "-50%",
                left: "-50%",
              }}
            />
          )}
          {!String(media.thumbnail).match(/\.mp4/) && (
            <Media
              thumbnail={`https://safeimage.buffer.com/500x/${media.thumbnail}`}
            />
          )}
          <TypeIcon>
            <MediaIcon type={type} />
          </TypeIcon>
        </MediaContainer>
      );
    }
    if (type === "carousel_album") {
      return (
        <MediaContainer>
          <Media
            thumbnail={`https://safeimage.buffer.com/500x/${media.thumbnail}`}
          />
          <TypeIcon>
            <MediaIcon type={type} />
          </TypeIcon>
        </MediaContainer>
      );
    }

    return media.thumbnail ? (
      <Media
        thumbnail={`https://safeimage.buffer.com/500x/${media.thumbnail}`}
      />
    ) : (
      <Empty>
        <Text color="lightSlate">No media</Text>
      </Empty>
    );
  }

  return <Container>{getThumbnail()}</Container>;
};

Attachment.defaultProps = {
  media: null,
};

Attachment.propTypes = {
  type: PropTypes.string.isRequired,
  media: PropTypes.shape({
    thumbnail: PropTypes.String,
    picture: PropTypes.String,
  }),
};

export default Attachment;
