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

import { format } from 'date-fns';
import { useDrawerLayer } from '@material-hu/components/layers/Drawers';

import { type AssignTemplateFormData } from '../../../hooks/useAssignTemplateDrawer';
import { useAssignTemplateMutation } from '../../../hooks/useAssignTemplateMutation';
import AssignTemplateDrawerContent from './AssignTemplateDrawerContent';

const INITIAL_VALUES: AssignTemplateFormData = {
  collaborators: [],
  startDate: null,
  templateId: null,
  templateName: '',
  repeatTemplate: false,
  includeHolidays: false,
};

const AssignTemplateDrawerShell = () => {
  const { closeDrawer } = useDrawerLayer();

  const form = useForm<AssignTemplateFormData>({
    defaultValues: { ...INITIAL_VALUES },
    mode: 'onSubmit',
  });

  const handleCleanup = () => {
    closeDrawer();
    form.reset({ ...INITIAL_VALUES });
  };

  const { assignTemplateMutation, isAssigningTemplate } =
    useAssignTemplateMutation({
      onSuccessCleanup: handleCleanup,
    });

  const submitForm = form.handleSubmit((data: AssignTemplateFormData) => {
    if (!data.templateId || !data.startDate) return;
    assignTemplateMutation({
      id: data.templateId,
      userIds: data.collaborators.map(c => Number(c.value)),
      startDate: format(data.startDate, 'yyyy-MM-dd'),
      templateName: data.templateName,
    });
  });

  const values = form.watch();
  const isSubmitEnabled =
    values.collaborators.length > 0 &&
    values.startDate !== null &&
    values.templateId !== null;

  return (
    <FormProvider {...form}>
      <AssignTemplateDrawerContent
        onSubmit={submitForm}
        onCancel={handleCleanup}
        isSubmitting={isAssigningTemplate}
        isSubmitEnabled={isSubmitEnabled}
      />
    </FormProvider>
  );
};

export default AssignTemplateDrawerShell;
