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

import { IconFilter } from '@material-hu/icons/tabler';

import Badge from '@material-hu/components/design-system/Badge';
import Button from '@material-hu/components/design-system/Buttons/Button';
import { useDrawerLayer } from '@material-hu/components/layers/Drawers';

import { EMPTY_FILTER_VALUES } from 'src/pages/dashboard/acknowledgements/constants';
import { useKudosRankingFilters } from 'src/pages/dashboard/acknowledgements/hooks/useKudosRankingFilters';
import { type KudosRankingFilterValues } from 'src/pages/dashboard/acknowledgements/types';
import { createKudosFilterResolver } from 'src/pages/dashboard/acknowledgements/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { RankingFilterDrawer } from './RankingFilterDrawer';

export const RankingFilters = () => {
  const { t } = useLokaliseTranslation('acknowledgements');
  const { openDrawer, closeDrawer } = useDrawerLayer();

  const { currentFormValues, setFilters, clearFilters, appliedFiltersCount } =
    useKudosRankingFilters();

  const resolver = useMemo(() => createKudosFilterResolver(t), [t]);

  const form = useForm<KudosRankingFilterValues>({
    defaultValues: EMPTY_FILTER_VALUES,
    resolver,
    mode: 'onChange',
  });

  const { reset } = form;

  const handleSubmitFilter = form.handleSubmit(values => {
    setFilters(values);
    closeDrawer();
  });

  const handleCleanFilters = () => {
    clearFilters();
    reset(EMPTY_FILTER_VALUES);
  };

  const handleShowDrawer = () => {
    reset(currentFormValues);
    openDrawer({
      content: (
        <FormProvider {...form}>
          <RankingFilterDrawer
            onSubmit={handleSubmitFilter}
            onClean={handleCleanFilters}
            onClose={closeDrawer}
          />
        </FormProvider>
      ),
    });
  };

  return (
    <Badge
      badgeContent={appliedFiltersCount}
      color="primary"
    >
      <Button
        variant="outlined"
        startIcon={<IconFilter />}
        onClick={handleShowDrawer}
      >
        {t('filter')}
      </Button>
    </Badge>
  );
};
