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

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

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

import { useFormCreation } from '../../../contexts/FormCreation';
import { newServiceItemFields } from '../../../forms';

type DateFormatOption = {
  label: string;
  value: string;
};

const DateOptions = () => {
  const { t } = useLokaliseTranslation('service_management');
  const { selected } = useFormCreation();
  const { watch, setValue } = useFormContext();

  const dateFormatName = newServiceItemFields.form.sections.questions.pattern(
    selected.section,
    selected.question,
  );

  const options: DateFormatOption[] = [
    { label: t('date_format_full'), value: 'yyyy-MM-dd' },
    { label: t('date_format_month_year'), value: 'yyyy-MM' },
  ];

  const watchedValue: string = watch(dateFormatName);
  const selectedOption =
    options.find(o => o.value === watchedValue) ?? options[0];

  return (
    <HuAutocomplete
      value={selectedOption}
      options={options}
      onChange={(option: DateFormatOption | null) => {
        if (option) setValue(dateFormatName, option.value);
      }}
      label={t('format')}
      disableClearable
      isServerFiltered={false}
    />
  );
};

export default DateOptions;
