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

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

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

import SortAttachmentsFormContent from '../components/SortAttachmentsFormContent';

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

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

  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('attachment.sort.title'),
      primaryButtonProps: {
        children: t('save'),
        type: 'submit',
      },
      secondaryButtonProps: {
        children: t('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,
  };
};

export default useSortAttachmentsDrawer;
