import { useState } from 'react';

import Box from '@material-hu/mui/Box';
import CardActionArea from '@material-hu/mui/CardActionArea';
import CardMedia from '@material-hu/mui/CardMedia';
import Dialog from '@material-hu/mui/Dialog';

import { Attachment } from 'src/types/attachments';

type Props = {
  media: Attachment;
};

const Media = ({ media: { url, type, name, width } }: Props) => {
  const [expandMedia, setExpandMedia] = useState(false);

  const renderMedia = () => (
    <CardMedia
      src={url}
      component={type === 'VIDEO' ? 'video' : 'img'}
      alt={name}
      width={width}
      controls
      sx={{
        height: '100%',
        objectFit: 'contain',
      }}
    />
  );

  return (
    <Box sx={{ height: 200 }}>
      {type === 'VIDEO' ? (
        renderMedia()
      ) : (
        <CardActionArea
          onClick={() => setExpandMedia(true)}
          sx={{ height: '100%' }}
        >
          {renderMedia()}
        </CardActionArea>
      )}
      <Dialog
        onClose={() => setExpandMedia(false)}
        open={expandMedia}
      >
        {renderMedia()}
      </Dialog>
    </Box>
  );
};

export default Media;
