import React from 'react';
import { useTheme } from 'styled-components';
import { WarningIcon } from '../../icons';
import FilledArrowCircleRight from '../../icons/FilledArrowCircleRight';
import FilledCloseIcon from '../../icons/FilledCloseIcon';
import Typography from '../Typography';
import { ErrorWrapper, IconWrapper, InputField, InputWrapper } from './styles';

export type InputIconState = 'CLEARABLE' | 'SUBMITABLE' | 'ERROR';

type RoundedInputProps = {
  errorMessage?: string;
  inputIconState: InputIconState;
  onClear?: () => void;
  onEnter?: () => void;
  onValueChange: (value: string) => void;
  isError: boolean;
  value: string;
  placeholder?: string;
};

const RoundedInput: React.FC<RoundedInputProps> = ({
  placeholder,
  errorMessage,
  inputIconState,
  onClear,
  onEnter,
  onValueChange,
  isError,
  value,
}) => {
  const { colors } = useTheme();

  const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    onValueChange(e.target.value);
  };

  const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleIconClick();
    }
  };
  const handleIconClick = () => {
    if (inputIconState === 'CLEARABLE') {
      onClear?.();
    } else if (inputIconState === 'SUBMITABLE') {
      onEnter?.();
    }
  };

  return (
    <>
      <InputWrapper isError={isError}>
        <InputField
          value={value}
          onChange={onInputChange}
          type="text"
          placeholder={placeholder}
          onKeyDown={onInputKeyDown}
        />
        <IconWrapper onClick={handleIconClick}>
          {inputIconState === 'CLEARABLE' && (
            <FilledCloseIcon color={colors.neutral[500]} />
          )}
          {inputIconState === 'SUBMITABLE' && (
            <FilledArrowCircleRight color={colors.neutral[800]} />
          )}
        </IconWrapper>
      </InputWrapper>
      {isError && errorMessage && (
        <ErrorWrapper>
          <WarningIcon height={16} width={16} />
          <Typography variant="utility5" color={colors.error[700]}>
            {errorMessage}
          </Typography>
        </ErrorWrapper>
      )}
    </>
  );
};

export default RoundedInput;
