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

import ListItem from '@material-hu/mui/ListItem';
import ListItemText from '@material-hu/mui/ListItemText';
import Typography from '@material-hu/mui/Typography';

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

import FormAutocomplete from 'src/components/FormInputs/FormAutocomplete';

import { TIMEZONES } from '../constants';

const TimezoneInput = () => {
  const { t } = useLokaliseTranslation('authentication');
  const [timezoneSearch, setTimezoneSearch] = useState('');

  const {
    formState: { errors },
  } = useFormContext();

  return (
    <>
      <FormAutocomplete
        name="timezone"
        limitTags={2}
        options={TIMEZONES}
        isOptionEqualToValue={(option, value) => option.id === value.id}
        getOptionLabel={option => option.label}
        renderOption={(renderProps, option) => (
          <ListItem
            {...renderProps}
            key={option.id}
          >
            <ListItemText
              primary={option.label}
              primaryTypographyProps={{
                color: 'textPrimary',
                noWrap: true,
                variant: 'subtitle2',
              }}
            />
          </ListItem>
        )}
        filterOptions={timezoneOption =>
          timezoneOption.filter(tz =>
            tz.label.toLowerCase().includes(timezoneSearch.toLowerCase()),
          )
        }
        clearOnBlur={false}
        onInputChange={(_, value) => {
          setTimezoneSearch(value);
        }}
        textFieldProps={{
          placeholder: t('SELECT'),
        }}
        rules={{
          required: t('MANDATORY_FIELD'),
        }}
        showErrorText={false}
      />
      {errors?.timezone && (
        <Typography sx={{ color: 'red', mt: 1, ml: 1 }}>
          {errors?.timezone.message as string}
        </Typography>
      )}
    </>
  );
};

export default TimezoneInput;
