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

import { type GetDrawerConfiguration, useDrawerV2 } from '@hooks/useDrawerV2';
import {
  type SortAttachmentsData,
  type SortableAttachment,
} from '@src/types/attachments';

import SortAttachmentsFormContent from './components/SortAttachmentsFormContent';

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

/** Provides a drawer for reordering attachments via drag-and-drop. */
export const useSortAttachmentsDrawer = () => {
  const { t } = useTranslation();

  const form = useForm<SortAttachmentsData>({
    defaultValues: { attachments: [] },
  });

  const { handleSubmit, reset } = form;

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

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

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

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

  const handleShow = (props: Partial<SortAttachmentsDrawerProps>) => {
    reset(
      { attachments: props.attachments || [] },
      { keepDefaultValues: true },
    );
    showSortAttachmentsDrawer(props);
  };

  const {
    drawer: sortDrawer,
    showDrawer: showSortAttachmentsDrawer,
    closeDrawer: closeSortAttachmentsDrawer,
  } = useDrawerV2<SortAttachmentsDrawerProps>(getDrawerConfiguration);

  return {
    sortAttachmentsDrawer: <FormProvider {...form}>{sortDrawer}</FormProvider>,
    showSortAttachmentsDrawer: handleShow,
    closeSortAttachmentsDrawer,
  };
};
