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

import { uniqueId } from 'lodash-es';
import {
  type GetDrawerConfiguration,
  useDrawerV2,
} from '@material-hu/hooks/useDrawerV2';

import {
  type AddAttachmentData,
  type SortableAttachment,
} from 'src/types/attachments';
import { useLokaliseTranslation } from 'src/utils/i18n';

import AddAttachmentFormContent from '../components/AddAttachmentFormContent';

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

export const useAddAttachmentDrawer = () => {
  const { t } = useLokaliseTranslation('general');

  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('attachment.add.title_long_other'),
      primaryButtonProps: {
        children: t('save'),
        disabled: uploading,
        type: 'submit',
      },
      secondaryButtonProps: {
        children: t('cancel'),
        onClick: handleCancel,
      },
      children: <AddAttachmentFormContent />,
    };
  };

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

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

export default useAddAttachmentDrawer;
