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

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

import { useLokaliseTranslation } from 'src/utils/i18n';

import CourseFilterForm from '../List/components/CourseFilterForm';
import { type CourseFilters } from '../types';

import { type TParams as GetCoursesParams } from './useGetCourses';

export type CourseFilterDrawerProps = {
  onSave: (filters: CourseFilters) => void;
  onClear: (filters: CourseFilters) => void;
};

const useCourseFilterDrawer = (params: GetCoursesParams) => {
  const { t } = useLokaliseTranslation('learning');

  const form = useForm<CourseFilters>({
    defaultValues: {
      sort: params?.sort ?? '',
      type: params?.type ?? '',
    },
    mode: 'onChange',
  });

  const { handleSubmit, reset } = form;

  const getDrawerConfiguration: GetDrawerConfiguration<
    CourseFilterDrawerProps
  > = props => {
    const submit = (filters: CourseFilters) => {
      closeCourseFilterDrawer();
      props.onSave(filters);
    };

    const clear = () => {
      props.onClear({ sort: '', type: '' });
      reset({ sort: '', type: '' });
      closeCourseFilterDrawer();
    };

    const primaryButtonProps = {
      children: t('general:apply'),
      onClick: handleSubmit(submit),
      sx: { width: '100%' },
    };

    const secondaryButtonProps = {
      children: t('general:reset_filters'),
      onClick: handleSubmit(clear),
      sx: { width: '100%' },
    };

    return {
      ...props,
      title: t('general:filter_by'),
      primaryButtonProps,
      secondaryButtonProps,
      children: (
        <FormProvider {...form}>
          <CourseFilterForm />
        </FormProvider>
      ),
    };
  };

  const {
    drawer: courseFilterDrawer,
    showDrawer: showCourseFilterDrawer,
    closeDrawer: closeCourseFilterDrawer,
  } = useDrawerV2<CourseFilterDrawerProps>(getDrawerConfiguration);

  return {
    courseFilterDrawer,
    showCourseFilterDrawer,
    closeCourseFilterDrawer,
  };
};

export default useCourseFilterDrawer;
