import { FC, useRef } from 'react';

import Compressor from 'compressorjs';

import CloseIcon from '@material-hu/icons/material/Close';
import FileUploadIcon from '@material-hu/icons/material/FileUpload';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import Input from '@material-hu/mui/Input';
import Typography from '@material-hu/mui/Typography';

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

import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';
import { ImageData } from 'src/types/recognitions';

const MAX_SIZE_BYTES = 4096 * 1024;
const QUALITY = 0.7;
const MAX_SIZE = 1280;

export type ImageControlProps = {
  image: ImageData;
  title: string;
  onAddImage?: (image: ImageData) => void;
  isReadOnly?: boolean;
};

export const ImageControl: FC<ImageControlProps> = props => {
  const { image, title, onAddImage, isReadOnly = false } = props;

  const { t } = useTranslation();

  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const handleImageChange = e => {
    const file = e.target.files[0];
    if (file) {
      const fileName = file.name || 'image.png';
      new Compressor(file, {
        quality: QUALITY,
        convertSize: MAX_SIZE_BYTES,
        maxHeight: MAX_SIZE,
        maxWidth: MAX_SIZE,
        success: result => {
          const reader = new FileReader();
          reader.onloadend = () => {
            onAddImage({
              fileName,
              imageData: reader.result as string,
            });
          };
          reader.readAsDataURL(result);
        },
      });
    }
  };

  const removeImage = () => onAddImage(null);

  const handleAttach = (): void => {
    fileInputRef.current.click();
  };

  return (
    <Box sx={{ mt: 2, pl: 1 }}>
      <Box sx={{ mb: 1 }}>
        <Typography
          color="textPrimary"
          variant="h5"
          sx={{ fontSize: '16px !important' }}
        >
          {title}
        </Typography>
      </Box>
      {!image && !isReadOnly && (
        <Button
          sx={{ display: 'flex', alignItems: 'center' }}
          onClick={handleAttach}
        >
          <FileUploadIcon sx={{ mr: 1 }} />
          {t('UPLOAD_IMAGE')}
        </Button>
      )}
      {image && (
        <Box sx={{ position: 'relative', width: 'fit-content' }}>
          <img
            src={image.imageData}
            alt={image.fileName}
            style={{
              height: '200px',
              marginTop: '10px',
              marginBottom: '10px',
              maxWidth: '400px',
            }}
          />
          {!isReadOnly && (
            <IconButton
              onClick={removeImage}
              sx={{
                position: 'absolute',
                backgroundColor: '#6a778b',
                p: '2px',
                right: '0px',
              }}
            >
              <CloseIcon
                fontSize="small"
                sx={{ color: '#FFFFFF' }}
              />
            </IconButton>
          )}
        </Box>
      )}
      <Input
        type="file"
        inputRef={fileInputRef}
        sx={{ display: 'none' }}
        onChange={handleImageChange}
        inputProps={{ accept: 'image/*' }}
      />
    </Box>
  );
};

export default ImageControl;
