import React, { useRef, useState } from 'react';
import { useTheme } from 'styled-components';
import { CloseIcon, SearchIcon } from '../../icons';
import Button from '../Button';
import CircleLoader from '../CircleLoader';
import { ISearchInputProps } from './interfaces';
import {
  ClearButtonWrapper,
  IconWrapper,
  SearchButtonWrapper,
  StyledInput,
  Wrapper,
} from './styles';

const SearchInput = ({
  value,
  placeholder,
  icon,
  isLoading,
  isClearable = true,
  isMobile = false,
  onChange,
  onClear,
  onFocus,
  onBlur,
  onSearchClick,
  onKeyDown,
  iconSize,
  inputHeight,
  inputWidth,
  fontSize,
}: ISearchInputProps) => {
  const theme = useTheme();
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [isFocused, setIsFocused] = useState(false);
  const showClear = Boolean(isClearable && value);

  const handleFocus = () => {
    setIsFocused(true);
    onFocus?.();
  };

  const handleBlur = () => {
    setIsFocused(false);
    onBlur?.();
  };

  const handleKeydown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' || e.code === 'Enter' || e.keyCode === 13) {
      e.preventDefault();
      e.stopPropagation();
      onSearchClick?.();
    }
    onKeyDown?.(e);
  };

  return (
    <Wrapper width={inputWidth} isMobile={isMobile}>
      <IconWrapper isMobile={isMobile}>
        {isLoading ? (
          <CircleLoader size={isMobile ? 14 : 22} />
        ) : (
          icon || (
            <SearchIcon
              color={
                isFocused
                  ? theme.colors.primary[800]
                  : theme.colors.neutral[400]
              }
              width={iconSize ? iconSize : isMobile ? 20 : 28}
              height={iconSize ? iconSize : isMobile ? 20 : 28}
            />
          )
        )}
      </IconWrapper>

      <StyledInput
        type="text"
        ref={inputRef}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        onFocus={handleFocus}
        onBlur={handleBlur}
        isMobile={isMobile}
        showClear={showClear}
        onKeyDown={handleKeydown}
        fontSize={fontSize}
        width={inputWidth}
        height={inputHeight}
      />

      {showClear && (
        <ClearButtonWrapper isMobile={isMobile}>
          <button role="button" onClick={onClear}>
            <CloseIcon />
          </button>
        </ClearButtonWrapper>
      )}

      <SearchButtonWrapper isMobile={isMobile}>
        <Button
          variant="primary-neutral"
          title="Search"
          size={isMobile ? 'default' : 'small'}
          height={isMobile ? 40 : 30}
          width={isMobile ? 74 : 66}
          fontWeight={500}
          onClick={onSearchClick}
        />
      </SearchButtonWrapper>
    </Wrapper>
  );
};

export default SearchInput;
