import React, { useEffect, useRef, useState } from 'react';
import { RxMagnifyingGlass } from 'react-icons/rx';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { uiFonts } from '../../constants/uiFonts';
import { IStyles } from '../Chat/Chat';
import { Column } from '../shared/Column';
import { Ellipsis } from '../shared/Ellipsis';
import { PrivateChatCharacter } from './types';

interface ISearchCharacterProps {
  onFocus?: () => void;
  onBlur?: () => void;
  onChangeCharacterName: (characterName: string) => void;
  styles?: IStyles;
  recentCharacters?: PrivateChatCharacter[];
  onCharacterClick?: (character: PrivateChatCharacter) => void;
  hideSearchCharacterUI: () => void;
}

export const SearchCharacter = ({
  onChangeCharacterName,
  onBlur,
  onFocus,
  recentCharacters,
  hideSearchCharacterUI,
  onCharacterClick,
  styles = {
    textColor: '#c65102',
    buttonColor: '#005b96',
    buttonBackgroundColor: 'rgba(0,0,0,.2)',
    width: '80%',
    height: 'auto',
  },
}: ISearchCharacterProps) => {
  const [characterName, setCharacterName] = useState('');
  const searchCharacterRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchCharacterRef.current) {
        searchCharacterRef.current.focus();
      }
    }, 100);

    return () => clearTimeout(timer);
  }, []);

  const handleSubmit = (event: React.SyntheticEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!characterName || characterName.trim() === '') return;
    onChangeCharacterName(characterName);
  };

  const handleCharacterClick = (character: PrivateChatCharacter) => {
    if (!onCharacterClick) return;
    setCharacterName('');
    onCharacterClick(character);
    hideSearchCharacterUI();
  };

  return (
    <SearchContainer>
      <Form onSubmit={handleSubmit}>
        <Column flex={70}>
          <TextField
            value={characterName}
            ref={searchCharacterRef}
            id="characterName"
            name="characterName"
            onChange={e => {
              setCharacterName(e.target.value);
              onChangeCharacterName(e.target.value);
            }}
            placeholder="Search for a character..."
            height={20}
            type="text"
            autoComplete="off"
            onFocus={onFocus}
            onBlur={onBlur}
            onPointerDown={onFocus}
          />
        </Column>
        <Column justifyContent="flex-end">
          <SearchButton
            type="submit"
            buttonColor={styles?.buttonColor || '#005b96'}
            buttonBackgroundColor={
              styles?.buttonBackgroundColor || 'rgba(0,0,0,.5)'
            }
            id="chat-send-button"
            style={{ borderRadius: '20%' }}
          >
            <RxMagnifyingGlass size={15} />
          </SearchButton>
        </Column>
      </Form>

      {recentCharacters && recentCharacters.length > 0 && (
        <ListContainer>
          {recentCharacters.map(character => (
            <ListElement
              onPointerDown={() => handleCharacterClick(character)}
              key={character._id}
            >
              <Ellipsis maxWidth="150px" maxLines={1}>
                {character.name}
              </Ellipsis>
            </ListElement>
          ))}
        </ListContainer>
      )}
    </SearchContainer>
  );
};

interface IButtonProps {
  buttonColor: string;
  buttonBackgroundColor: string;
}

const SearchContainer = styled.div`
  width: 100%;
`;

const Form = styled.form`
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
`;

const TextField = styled.input`
  width: 100%;
  background-color: rgba(0, 0, 0, 0.25) !important;
  border: none !important;
  max-height: 28px !important;
`;

const SearchButton = styled.button<IButtonProps>`
  color: ${({ buttonColor }) => buttonColor};
  background-color: ${({ buttonBackgroundColor }) => buttonBackgroundColor};
  width: 28px;
  height: 28px;
  border: none !important;
`;

const ListContainer = styled.ul`
  border: none;
  overflow-y: scroll;
  list-style: none;
  padding: 0;
`;

const ListElement = styled.li`
  margin: 0.5rem 0 !important;
  font-size: ${uiFonts.size.small};
  padding: 0.5rem 2px;

  &:hover {
    color: #ff0;
    background-color: ${uiColors.darkGray};
  }

  button {
    all: unset;
  }
`;
