import {useCallback} from 'react';
import {useController, useFormContext} from 'react-hook-form';
import {Attachment} from '@interfaces/attachments';

import {PublishPostField} from '../interfaces';

export const useDisplayAttachments = () => {
  const {clearErrors} = useFormContext();

  const {
    field: {onChange: onChangeMultimedia, value: multimedia},
  } = useController({name: PublishPostField.Multimedia});
  const {
    field: {onChange: onChangeFiles, value: files},
  } = useController({name: PublishPostField.Files});
  const {
    field: {onChange: onChangeAttachmentsSize, value: attachmentsSize},
    fieldState: {error: attachmentsSizeError},
  } = useController({name: PublishPostField.AttachmentsSize});

  const onClearSizeError = useCallback(() => {
    clearErrors(PublishPostField.AttachmentsSize);
  }, [clearErrors]);

  const onDeleteMultimedia = useCallback(
    (attachment: Attachment) => {
      onChangeMultimedia(
        multimedia.filter((item: Attachment) => item.id !== attachment.id),
      );
      onChangeAttachmentsSize(attachmentsSize - attachment.bytes!);
    },
    [attachmentsSize, multimedia, onChangeAttachmentsSize, onChangeMultimedia],
  );

  const onDeleteFile = useCallback(
    (file: Attachment) => {
      onChangeFiles(files.filter((item: Attachment) => item.id !== file.id));
      onChangeAttachmentsSize(attachmentsSize - file.bytes!);
    },
    [attachmentsSize, files, onChangeAttachmentsSize, onChangeFiles],
  );

  return {
    files,
    hasMaxSizeError: !!attachmentsSizeError,
    multimedia,
    onClearSizeError,
    onDeleteFile,
    onDeleteMultimedia,
  };
};
