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

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import FilterListOutlined from '@material-hu/icons/material/FilterListOutlined';
import Badge from '@material-hu/mui/Badge';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuSkeleton from '@material-hu/components/design-system/Skeleton';

import useNewTheme from 'src/hooks/useNewTheme';
import { getActiveFilters } from 'src/utils/formUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { appliedFiltersNumber } from 'src/components/AdvancedFilter/utils';
import FormCheckbox from 'src/components/FormInputs/FormCheckbox';

import { type Category } from '../../../../Settings/Categories/types';
import useGetCourseCategories from '../../../hooks/useGetCourseCategories';
import {
  type CategoriesRecord,
  type CoursesListParams,
  NoCategory,
} from '../../../types';
import {
  buildCategoryFilterValues,
  getCategoryFiltersParams,
} from '../../utils';

type CategoryFilterDrawerProps = {
  setPartialParams: (values: Partial<CoursesListParams> | null) => void;
  activeFiltersIds: string[];
};

type FilterDrawerProps = {
  categories: Category[];
};

function FilterDrawer({ categories }: FilterDrawerProps) {
  const { t } = useLokaliseTranslation('learning');
  const NewThemeProvider = useNewTheme();

  if (!categories) return null;

  return (
    <Stack sx={{ gap: 1.5, flexGrow: 1 }}>
      <NewThemeProvider>
        <Typography
          component="h2"
          variant="subtitle1"
        >
          {t('common.category_other')}
        </Typography>
        <Stack
          component="ul"
          sx={{ gap: 1.5 }}
        >
          {categories.map(category => (
            <FormCheckbox
              key={category.id}
              sx={{
                padding: 0,
                marginLeft: 1,
                marginRight: 0.5,
              }}
              name={category.id?.toString() ?? ''}
              label={category.name}
            />
          ))}
        </Stack>
      </NewThemeProvider>
    </Stack>
  );
}

export default function CategoryFilterDrawer({
  setPartialParams,
  activeFiltersIds,
}: CategoryFilterDrawerProps) {
  const { t } = useLokaliseTranslation('learning');

  const { data: courseCategories, isLoading: isLoadingCategories } =
    useGetCourseCategories();

  const noCategoryOption = {
    id: Number(NoCategory.ID),
    name: t('common.no_category'),
  };

  const categories = [...(courseCategories ?? []), noCategoryOption];

  const form = useForm<CategoriesRecord>({
    defaultValues: buildCategoryFilterValues(categories, activeFiltersIds),
  });

  const handleClearFilters = () => {
    form.reset(buildCategoryFilterValues(categories, activeFiltersIds, true));
    setPartialParams(getCategoryFiltersParams([]));
    closeCategoryFiltersDrawer();
  };

  const handleApplyFilters = form.handleSubmit((data: CategoriesRecord) => {
    const activeFilters = getActiveFilters(data);
    setPartialParams(getCategoryFiltersParams(activeFilters));
    closeCategoryFiltersDrawer();
  });

  const {
    showDrawer: showCategoryFiltersDrawer,
    drawer: categoryFiltersDrawer,
    closeDrawer: closeCategoryFiltersDrawer,
  } = useDrawerV2(() => ({
    children: <FilterDrawer categories={categories} />,
    title: t('general:filter_by'),
    primaryButtonProps: {
      children: t('general:apply'),
      fullWidth: true,
      onClick: handleApplyFilters,
    },
    secondaryButtonProps: {
      children: t('general:clean_filters'),
      fullWidth: true,
      onClick: handleClearFilters,
    },
  }));

  if (isLoadingCategories) {
    return (
      <HuSkeleton
        variant="rectangular"
        sx={{ borderRadius: 2, width: 150, height: 42 }}
      />
    );
  }

  if (!categories.length) return null;

  const appliedFiltersCount = appliedFiltersNumber(form.getValues());

  return (
    <FormProvider {...form}>
      {categoryFiltersDrawer}
      <Button
        variant="outlined"
        startIcon={<FilterListOutlined />}
        size="large"
        sx={{ textWrap: 'nowrap', maxHeight: '42px' }}
        onClick={showCategoryFiltersDrawer}
        endIcon={
          <Badge
            sx={{ mx: appliedFiltersCount && 1.5 }}
            color="primary"
            badgeContent={appliedFiltersCount}
          />
        }
      >
        {t('general:filter_by')}
      </Button>
    </FormProvider>
  );
}
