import { useFormContext, useWatch } from 'react-hook-form';

import Typography from '@material-hu/mui/Typography';

import FormCoverPictureUploader from '@material-hu/components/composed-components/CoverPictureUploader/form';
import CardContainer from '@material-hu/components/design-system/CardContainer';

import { megabytesToBytes } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  LIBRARY_HOME_COVER_CROP_HEIGHT,
  LIBRARY_HOME_COVER_CROP_WIDTH,
  LIBRARY_HOME_COVER_TOOLTIP_HEIGHT,
  LIBRARY_HOME_COVER_TOOLTIP_MAX_MB,
  LIBRARY_HOME_COVER_TOOLTIP_WIDTH,
} from '../../constants';

import { type LibraryHomeEditFormValues } from './libraryHomeEditForm';

type HomeCoverPictureProps = {
  defaultCoverSrc: string;
  disabled?: boolean;
};

export const HomeCoverPicture = ({
  defaultCoverSrc,
  disabled = false,
}: HomeCoverPictureProps) => {
  const { t } = useLokaliseTranslation(['general']);
  const { control } = useFormContext<LibraryHomeEditFormValues>();

  const cover = useWatch({
    control,
    name: 'cover',
  });

  const hasCover = Boolean(cover?.cropped);

  return (
    <CardContainer
      fullWidth
      color="grey"
    >
      <Typography sx={{ mb: 1, fontWeight: 'fontWeightSemiBold' }}>
        {t('cover_picture.title')}
      </Typography>
      <FormCoverPictureUploader
        name="cover"
        uploaderProps={{
          aspectRatio: '4/1',
          defaultSrc: defaultCoverSrc,
          disabled,
          maxSize: megabytesToBytes(LIBRARY_HOME_COVER_TOOLTIP_MAX_MB),
          recommendedHeight: LIBRARY_HOME_COVER_CROP_HEIGHT,
          recommendedWidth: LIBRARY_HOME_COVER_CROP_WIDTH,
          recommendedSizeTooltip: !hasCover
            ? {
                format: ['JPG', 'PNG'],
                size: `${LIBRARY_HOME_COVER_TOOLTIP_WIDTH}x${LIBRARY_HOME_COVER_TOOLTIP_HEIGHT}`,
              }
            : undefined,
          sx: {
            '& .HuCoverPictureUploader-image': {
              p: 0,
              borderRadius: 2,
            },
          },
        }}
      />
    </CardContainer>
  );
};
