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

import { type GetDrawerConfiguration, useDrawerV2 } from '@hooks/useDrawerV2';
import {
  type Attachment,
  type UpdateAttachmentData,
} from '@src/types/attachments';
import { splitFileName } from '@utils/attachments';

import EditAttachmentFormContent from './components/EditAttachmentFormContent';

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

/** Provides a drawer for renaming an existing attachment. */
export const useEditAttachmentDrawer = (rules: ControllerProps['rules']) => {
  const { t } = useTranslation();
  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('general:attachment.rename.title'),
      primaryButtonProps: {
        children: t('general:save'),
        type: 'submit',
      },
      secondaryButtonProps: {
        children: t('general:cancel'),
        onClick: handleCancel,
      },
      children: <EditAttachmentFormContent rules={rules} />,
    };
  };

  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,
  };
};
