import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';

import { Typography } from '@mui/material';
import { sumBy } from 'lodash';

import { bytesToMB, megabytesToGB } from '../../../utils/bytes';

import { type FieldValues } from './CreatePost';

type MediaSizeProps = { maxInMB?: number };

export const MediaSize: FC<MediaSizeProps> = ({ maxInMB = 100 }) => {
  const form = useFormContext<FieldValues>();
  const { media, files } = form.watch();
  const size = Math.ceil(
    bytesToMB(
      sumBy([...media, ...files], f => f.file?.size || f.attachment!.bytes),
    ),
  );

  const maxInGB = Math.ceil(megabytesToGB(maxInMB));
  const sizeInGB = Math.ceil(megabytesToGB(size));

  return (
    !!size && (
      <Typography
        variant="globalS"
        sx={{ color: ({ palette }) => palette.new.text.neutral.lighter }}
      >
        {maxInMB > 1024 ? `${sizeInGB}/${maxInGB}GB` : `${size}/${maxInMB}MB`}
      </Typography>
    )
  );
};

export default MediaSize;
