import { FC, useRef } from 'react';
import { useFormContext, Controller } from 'react-hook-form';

import Box from '@material-hu/mui/Box';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Input from '@material-hu/mui/Input';
import Typography from '@material-hu/mui/Typography';

import humandLogo from 'src/assets/svg/humand.svg';
import { useLokaliseTranslation } from 'src/utils/i18n';

export const FormLogoInput: FC = () => {
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const { control, watch } = useFormContext();
  const { t } = useLokaliseTranslation('authentication');

  const companyLogo = watch('logo');

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

  const handleImageChange = async (e, onChange) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      onChange(file);
    }
  };

  return (
    <>
      <Controller
        control={control}
        name="logo"
        render={({ field: { onChange } }) => (
          <Box sx={{ border: '1px dashed #000', width: '100%' }}>
            <ButtonBase
              onClick={handleAttach}
              focusRipple
              sx={{ width: '100%' }}
            >
              <img
                src={
                  companyLogo === humandLogo
                    ? companyLogo
                    : URL.createObjectURL(companyLogo)
                }
                alt=""
                width="100%"
                height="60px"
              />
            </ButtonBase>
            <Input
              type="file"
              inputProps={{
                accept: 'image/png, image/jpg, image/jpeg',
              }}
              sx={{
                display: 'none',
              }}
              inputRef={fileInputRef}
              onChange={e => handleImageChange(e, onChange)}
            />
          </Box>
        )}
      />
      <Typography
        color="secondary"
        sx={{ fontSize: '12px', lineHeight: 1 }}
      >
        {t('LOGO_PLACEHOLDER')}
      </Typography>
    </>
  );
};

export default FormLogoInput;
