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

import {
  useDrawerV2,
  GetDrawerConfiguration,
} from '@material-hu/hooks/useDrawerV2';

import { Attachment, UpdateAttachmentData } from 'src/types/attachments';
import { splitFileName } from 'src/utils/attachments';
import { useLokaliseTranslation } from 'src/utils/i18n';

import EditAttachmentFormContent from '../components/EditAttachmentFormContent';

export type EditAttachmentDrawerProps = {
  onCancel?: (attachment: Attachment) => void;
  onConfirm?: (attachment: Attachment, values: UpdateAttachmentData) => void;
  attachment: Attachment;
};

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

  const form = useForm<UpdateAttachmentData>({
    defaultValues: {
      name: '',
      extension: '',
    },
  });

  const { handleSubmit, reset } = form;

  const getDrawerConfiguration: GetDrawerConfiguration<
    EditAttachmentDrawerProps
  > = ({ onConfirm, onCancel, attachment, ...props }) => {
    const submit = handleSubmit(values => {
      onConfirm?.(attachment, values);
      handleClose();
    });

    const handleClose = () => {
      closeEditAttachmentDrawer();
      reset();
    };

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

    return {
      ...props,
      component: 'form',
      onSubmit: submit,
      onClose: handleClose,
      title: t('attachment.rename.title'),
      primaryButtonProps: {
        children: t('save'),
        type: 'submit',
      },
      secondaryButtonProps: {
        children: t('cancel'),
        onClick: handleCancel,
      },
      children: <EditAttachmentFormContent />,
    };
  };

  const handleShow = (props: Partial<EditAttachmentDrawerProps>) => {
    reset(splitFileName(props.attachment?.name || ''), {
      keepDefaultValues: true,
    });
    showEditAttachmentDrawer(props);
  };

  const {
    drawer: editDrawer,
    showDrawer: showEditAttachmentDrawer,
    closeDrawer: closeEditAttachmentDrawer,
  } = useDrawerV2<EditAttachmentDrawerProps>(getDrawerConfiguration);

  return {
    editAttachmentDrawer: <FormProvider {...form}>{editDrawer}</FormProvider>,
    showEditAttachmentDrawer: handleShow,
    closeEditAttachmentDrawer,
  };
};

export default useEditAttachmentDrawer;
