import { FC } from 'react';
import { useFormContext } from 'react-hook-form';

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

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

import AdvancedFilter from 'src/components/AdvancedFilter/AdvancedFilter';
import { AutocompleteField } from 'src/components/AdvancedFilter/types';

type Props = {
  enableFieldName: string;
  fieldName: string;
  optionsList: AutocompleteField[];
  sectionTitle: string;
  sectionDescription?: string;
  multiple?: boolean;
  isServerFiltered?: boolean;
};

const ReportFieldsSelector: FC<Props> = props => {
  const {
    enableFieldName,
    fieldName,
    optionsList,
    sectionDescription = '',
    sectionTitle,
    multiple = false,
    isServerFiltered = true,
  } = props;
  const { t } = useLokaliseTranslation('time_tracker');
  const { watch } = useFormContext();
  const fields = watch(fieldName);
  const enableFields = watch(enableFieldName);

  const fieldPlaceholder: Record<string, string> = {
    segmentationGroups: 'segmentation_groups',
    profileFields: 'profile_fields',
    hourTypes: 'hour_types',
  };

  return (
    <AdvancedFilter
      name={enableFieldName}
      keyReset={fieldName}
      title={sectionTitle}
      description={sectionDescription}
      expanded={enableFields}
      multiple
    >
      <FormAutocomplete
        options={optionsList}
        name={fieldName}
        autocompleteProps={{
          placeholder:
            fields?.length === 0
              ? t('time_tracker:placeholder_field', {
                  context: fieldPlaceholder[fieldName],
                })
              : undefined,
          isServerFiltered,
          multiple,
          sx: {
            mt: 1,
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.tertiary,
          },
          noOptionsMessage: {
            title: t('time_tracker:autocomplete_no_results'),
          },
        }}
      />
    </AdvancedFilter>
  );
};

export default ReportFieldsSelector;
