import { useMemo, useState } from 'react';

import ListItem from '@material-hu/mui/ListItem';
import { fadeIn } from '@material-hu/utils/animations';

import FormAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete/form';

import { TruncatedCategoryPath } from 'src/pages/dashboard/Learning/Settings/Categories/List/components/CreateCategoryDrawer/TruncatedCategoryPath';

import {
  MAX_CATEGORIES_CHILDREN,
  MAX_CATEGORIES_DEPTH,
} from '../../../constants';
import useGetCategories from '../../../hooks/useGetCategories';
import { flattenCategoriesToOptions } from '../../../utils';

type CategoriesAutocompleteProps = {
  name: string;
  usage: 'createCategory' | 'listCategories';
  label: string;
  placeholder: string;
  disabled?: boolean;
};

const CategoriesAutocomplete = ({
  usage,
  name,
  label,
  placeholder,
  disabled,
}: CategoriesAutocompleteProps) => {
  const [inputSearch, setInputSearch] = useState('');

  const { categories, isFetching, handleFetchNextPage, hasNextPage } =
    useGetCategories({ q: inputSearch });

  const options = useMemo(
    () => flattenCategoriesToOptions(categories),
    [categories],
  );

  const filteredOptions = useMemo(() => {
    if (usage === 'createCategory') {
      // We only show the first 2 levels: Parent and children\
      return options.filter(
        option => (option.depth ?? 0) < MAX_CATEGORIES_DEPTH,
      );
    }
    return options;
  }, [options]);

  return (
    <FormAutocomplete
      name={name}
      options={filteredOptions}
      autocompleteProps={{
        onLoadMore: handleFetchNextPage,
        onInputChange: (_, value) => setInputSearch(value),
        inputValue: inputSearch,
        sx: { animation: `${fadeIn} 0.3s ease-in-out backwards` },
        label,
        placeholder,
        disabled,
        multiple: false,
        isServerFiltered: false,
        loading: isFetching,
        filterSelectedOptions: true,
        hasMoreOptions: hasNextPage,
        renderOption: (props, option) => {
          return (
            <ListItem
              {...props}
              key={option.value}
              sx={{ p: theme => `${theme.spacing(2)} !important` }}
            >
              <TruncatedCategoryPath
                option={option}
                showMaxDepthErrorMessage
                showErrors={usage === 'createCategory'}
              />
            </ListItem>
          );
        },
        getOptionDisabled: option => {
          if (!option.childrenCount || usage === 'listCategories') return false;
          return option.childrenCount >= MAX_CATEGORIES_CHILDREN;
        },
      }}
    />
  );
};

export default CategoriesAutocomplete;
