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

import WarningIcon from '@material-hu/icons/material/Warning';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Tooltip from '@material-hu/mui/Tooltip';

import XIcon from 'src/icons/X';
import { ReviewQuestionType } from 'src/types/performance';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

import OptionBullet from '../OptionBullet';

type Props = {
  index: number;
  onRemove?: Function;
  last: boolean;
  type: ReviewQuestionType;
};

const Option = ({ index, onRemove, last, type }: Props) => {
  const { t } = useLokaliseTranslation('performance');
  const name = `possibleAnswers.${index}.value` as const;
  const { setValue, watch } = useFormContext<{
    possibleAnswers: { value: string }[];
  }>();
  const { possibleAnswers } = watch();
  const currentOption = possibleAnswers[index];
  const [hasBeenBlurred, setHasBeenBlurred] = useState(false);
  const isRepeated =
    possibleAnswers.filter(o => o.value === currentOption.value).length > 1;
  const isJustCreated = !hasBeenBlurred;

  const onBlur = (newValue: string) => {
    if (isRepeated) {
      onRemove();
    }
    if (newValue === '') {
      if (possibleAnswers.length > 1) {
        onRemove();
      } else {
        setValue(name, 'Nueva opción 1', { shouldDirty: true });
      }
    }
    setHasBeenBlurred(true);
  };

  const onFocus = event => {
    if (isJustCreated) {
      event.target.select();
    }
  };

  return (
    <Stack
      direction="row"
      sx={{ alignItems: 'center', mb: 2 }}
    >
      <OptionBullet
        index={index}
        type={type}
      />
      <FormTextField
        name={name}
        variant="outlined"
        sx={{ mx: 1, ml: 2, backgroundColor: 'white' }}
        size="small"
        // value={currentOption}
        // @ts-ignore
        onBlur={onBlur}
        onFocus={onFocus}
        inputProps={{ maxLength: 510, style: { fontWeight: 400 } }}
      />
      {isRepeated && (
        <Tooltip title={t('questions.repeated_warning')}>
          <WarningIcon color="error" />
        </Tooltip>
      )}
      <IconButton
        onClick={() => onRemove()}
        disabled={last}
      >
        <XIcon fontSize="small" />
      </IconButton>
    </Stack>
  );
};

export default Option;
