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

import { upperFirst } from 'lodash-es';
import { useModal } from '@material-hu/hooks/useModal';

import RemoveCoverPictureModal from '../components/RemoveCoverPictureModal';

export const useCoverPicture = (name: string = 'coverPicture') => {
  const { setValue } = useFormContext();

  const showName = `show${upperFirst(name)}` as const;

  const showCoverPicture = useWatch({ name: showName });
  const coverPicture = useWatch({ name });

  const {
    modal: removeCoverPictureModal,
    showModal: showRemoveCoverPictureModal,
  } = useModal(RemoveCoverPictureModal);

  const removeCoverPictureValues = () => {
    setValue(showName, false);
    setValue(name, null);
  };

  const removeCoverPicture = () => {
    if (!coverPicture) return removeCoverPictureValues();
    showRemoveCoverPictureModal({ onConfirm: removeCoverPictureValues });
  };

  const addCoverPicture = () => setValue(showName, true);

  return {
    showCoverPicture,
    coverPicture,
    removeCoverPicture,
    addCoverPicture,
    removeCoverPictureModal,
  };
};

export default useCoverPicture;
