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

import Image from '@material-hu/components/composed-components/Image';

import { type ArticleFormValues } from 'src/pages/dashboard/HuLibraries/schemas';
import { getCoverPictureSrc } from 'src/pages/dashboard/HuLibraries/utils';

export const ArticleEditCover = () => {
  const { control } = useFormContext<ArticleFormValues>();

  const [showCoverPicture, coverPicture] = useWatch({
    control,
    name: ['showCoverPicture', 'coverPicture'],
  });

  const coverSrc = useMemo(
    () => getCoverPictureSrc(showCoverPicture, coverPicture),
    [showCoverPicture, coverPicture],
  );

  useEffect(() => {
    return () => {
      if (coverSrc && coverPicture?.file) URL.revokeObjectURL(coverSrc);
    };
  }, [coverSrc, coverPicture?.file]);

  if (!coverSrc) return null;

  return (
    <Image
      src={coverSrc}
      aspectRatio="4/1"
    />
  );
};
