import { FC } from 'react';

import { useTranslation } from 'react-i18next';

import DownloadIcon from '@material-hu/icons/material/Download';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { Attachment } from 'src/types/attachments';
import { getFileIcon } from 'src/utils/files';

export type FileAttachmentProps = {
  file: Attachment;
  extension: string;
  isLoading?: boolean;
};

const FileAttachment: FC<FileAttachmentProps> = props => {
  const { file, extension, isLoading = false } = props;

  const { t } = useTranslation('attachments');

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    event.stopPropagation();
    window.open(file.url, '_blank', 'noopener,noreferrer');
  };

  return (
    <Button
      onClick={handleClick}
      sx={{
        width: '100%',
        backgroundColor: '#f5f6f6',
        borderRadius: '16px',
        display: 'flex',
        justifyContent: 'space-between',
        '&:hover': {
          backgroundColor: '#f5f6f6',
        },
      }}
    >
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          p: 1,
          alignItems: 'center',
          width: '100%',
        }}
      >
        <Box sx={{ display: 'flex' }}>
          <img
            src={getFileIcon(file)}
            alt=""
            style={{ width: '28px', height: '30px' }}
          />
          <Box sx={{ width: '200px', textAlign: 'left', ml: 1 }}>
            <Typography
              sx={{
                fontSize: '14px',
                color: '#1D1C1D',
                fontWeight: 600,
                lineHeight: '16px',
              }}
            >
              {file.name}
            </Typography>
            <Typography
              sx={{
                fontSize: '11px',
                color: '#6c757d',
                textTransform: 'uppercase',
              }}
            >
              {t('file_description', {
                extension: extension,
                usage: file.size,
              })}
            </Typography>
          </Box>
        </Box>
        {isLoading && (
          <Box>
            <CircularProgress size={30} />
          </Box>
        )}
        {!isLoading && (
          <IconButton
            aria-label={file.name}
            onClick={handleClick}
            sx={{
              borderRadius: '4px',
              ml: 1,
              pr: 0,
            }}
          >
            <DownloadIcon
              sx={{ color: '#000000', width: '24px', height: '24px' }}
            />
          </IconButton>
        )}
      </Box>
    </Button>
  );
};

export default FileAttachment;
