import { type FC, useRef, useState } from 'react';

import ButtonBase from '@material-hu/mui/ButtonBase';
import { grey } from '@material-hu/mui/colors';
import Input, { type InputProps } from '@material-hu/mui/Input';
import Typography from '@material-hu/mui/Typography';

import { type Attachment, FileTypes } from 'src/types/attachments';
import { getAttachment } from 'src/utils/files';

export type FormImageProps = InputProps & {
  icon: any;
  baseColor?: string;
  label?: string;
  defaultImage?: Attachment;
  onChange: (file) => void;
};

/**
 * @deprecated This component does not implement Hugo's design system.
 */
const FormImage: FC<FormImageProps> = props => {
  const {
    name,
    icon,
    baseColor = grey[400],
    label = '',
    defaultImage = null,
    onChange,
    ...others
  } = props;

  const [image, setImage] = useState<Attachment | null>(defaultImage);

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

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

  const handleChange = async event => {
    const file = event.target.files[0];

    const newFile = {
      name: file.name,
      size: file.size,
      mime: file.type,
      fileObject: file,
      type: FileTypes.IMAGE,
    };

    setImage(getAttachment(newFile));
    onChange(newFile);
  };

  const inputSx = others.sx || {};

  return (
    <>
      <ButtonBase
        onClick={handleAttach}
        focusRipple
        sx={{
          width: '200px',
          height: '200px',
          borderRadius: '50%',
          backgroundColor: baseColor,
          '&:hover': {
            '& .MuiTypography-root': {
              opacity: 1,
            },
          },
          '& .MuiTypography-root': {
            color: 'white',
            width: '100%',
            height: '100%',
            borderRadius: '50%',
            position: 'absolute',
            opacity: 0,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            padding: '1rem',
            backgroundColor: `${grey[600]}be`,
          },
          '& .image': {
            width: '100%',
            height: '100%',
            borderRadius: '50%',
            objectFit: 'cover',
          },
        }}
      >
        {!image ? (
          icon
        ) : (
          <img
            className="image"
            src={image.url}
            alt=""
          />
        )}
        <Typography variant="button">{label}</Typography>
      </ButtonBase>
      <Input
        {...others}
        type="file"
        inputProps={{
          accept: 'image/png, image/jpg, image/jpeg',
        }}
        sx={{
          display: 'none',
          ...inputSx,
        }}
        inputRef={fileInputRef}
        onChange={handleChange}
      />
    </>
  );
};

export default FormImage;
