import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import { type GetDrawerConfiguration, useDrawerV2 } from '@hooks/useDrawerV2';
import {
  type AddAttachmentData,
  type SortableAttachment,
  type UploadFile,
} from '@src/types/attachments';
import { uniqueId } from 'lodash';

import AddAttachmentFormContent from './components/AddAttachmentFormContent';

export type AddAttachmentDrawerProps = {
  onCancel?: () => void;
  onConfirm?: (attachments: SortableAttachment[]) => void;
};

/** Provides a drawer for uploading and adding new attachments. */
export const useAddAttachmentDrawer = (upload?: UploadFile) => {
  const { t } = useTranslation();
  const form = useForm<AddAttachmentData>({
    defaultValues: { fileCards: [] },
  });

  const { handleSubmit, reset, control } = form;

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

  const getDrawerConfiguration: GetDrawerConfiguration<
    AddAttachmentDrawerProps
  > = ({ onConfirm, onCancel, ...props }) => {
    const submit = handleSubmit((values: AddAttachmentData) => {
      const attachments = values.fileCards
        .filter(
          fileCard => fileCard.status === 'success' && !!fileCard.attachment,
        )
        .map(
          fileCard =>
            ({
              ...fileCard.attachment,
              file: fileCard.file,
              id: -1 * Number(uniqueId()),
            }) as SortableAttachment,
        );

      onConfirm?.(attachments);
      handleClose();
    });

    const handleClose = () => {
      closeAddAttachmentDrawer();
      reset({ fileCards: [] });
    };

    const handleCancel = () => {
      onCancel?.();
      handleClose();
    };

    const uploading = fileCards.some(
      fileCard => fileCard.status === 'uploading',
    );

    return {
      ...props,
      component: 'form',
      onSubmit: submit,
      onClose: handleClose,
      title: t('general:attachment.add.title_long_other'),
      primaryButtonProps: {
        children: t('general:save'),
        disabled: uploading,
        type: 'submit',
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        onClick: handleCancel,
      },
      children: <AddAttachmentFormContent upload={upload} />,
    };
  };

  const {
    drawer: addDrawer,
    showDrawer: showAddAttachmentDrawer,
    closeDrawer: closeAddAttachmentDrawer,
  } = useDrawerV2<AddAttachmentDrawerProps>(getDrawerConfiguration);

  return {
    addAttachmentDrawer: <FormProvider {...form}>{addDrawer}</FormProvider>,
    showAddAttachmentDrawer,
    closeAddAttachmentDrawer,
  };
};
