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 '../../../Questions/components/OptionBullet';

type Props = {
  name: string;
  questionIndex: number;
  index: number;
  onRemove: Function;
  last: boolean;
  type: ReviewQuestionType;
  isGoalQuestion?: boolean;
};

const Option = ({
  isGoalQuestion = false,
  name,
  questionIndex,
  index,
  onRemove,
  last,
  type,
}: Props) => {
  const { t } = useLokaliseTranslation('performance');
  const prefix = isGoalQuestion ? name : `${name}.${questionIndex}`;
  const questionName = `${prefix}.possibleAnswers.${index}.value` as const;
  const { setValue, watch } = useFormContext();
  const questionObject = watch(name);
  const question = isGoalQuestion
    ? questionObject
    : questionObject[questionIndex];

  const answers: string[] = question.possibleAnswers.map(
    (a: { id: string; value: string }) => a.value,
  );
  const [hasBeenBlurred, setHasBeenBlurred] = useState(false);
  const isJustCreated = !hasBeenBlurred;

  const isRepeated = answers.filter(o => o === answers[index]).length > 1;

  const onBlur = (newValue: string) => {
    if (isRepeated) {
      onRemove();
    }
    if (newValue === '') {
      if (answers.length > 1) {
        onRemove();
      } else {
        setValue(questionName, t('templates.new_option_1'), {
          shouldDirty: true,
        });
      }
    }
    setHasBeenBlurred(true);
  };

  const onFocus = (
    event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    if (isJustCreated) {
      event.target.select();
    }
  };

  return (
    <Stack
      direction="row"
      sx={{ alignItems: 'center', mb: 2 }}
    >
      <OptionBullet
        index={index}
        type={type}
      />
      <FormTextField
        name={questionName}
        variant="outlined"
        sx={{ mx: 1, ml: 2, backgroundColor: 'white' }}
        size="small"
        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;
