import React, { FunctionComponent, useState } from 'react';
import cn from 'classnames';
import { FaSearch } from 'react-icons/fa';

import { NavbarRightPanelProps } from './types.d';
import { StyledIconButton, StyledInput } from '../StyledComponents';
import { useTheme } from '../Theme';

export const NavbarRightPanel: FunctionComponent<NavbarRightPanelProps> = ({
  buttons,
  className = '',
  search,
}): React.ReactElement => {
  const [isSearchActive, setIsSearchActive] = useState(false);
  const theme = useTheme();

  const toggleSearch = () => {
    setIsSearchActive((prevState) => !prevState);
  };

  const classNames = cn({
    header__group: true,
    [className]: !!className,
  });

  const searchClassNames = cn({
    header__search: true,
    'js-header-search': true,
    active: isSearchActive,
  });

  const renderSearch = () => {
    if (!search) return null;
    return (
      <form className={searchClassNames}>
        <button className="header__open js-header-open" type="button" onClick={toggleSearch}>
          <StyledIconButton className="icon icon-search" $theme={theme}>
            <FaSearch />
          </StyledIconButton>
        </button>
        <div className="header__wrap">
          <StyledInput
            className="header__input"
            type="text"
            name="search"
            value={search.searchPattern}
            placeholder={search.placeholder ?? 'Find'}
            onChange={search.onChange}
            $theme={theme}
          />
        </div>
      </form>
    );
  };

  return (
    <div className={classNames}>
      {renderSearch()}
      {buttons}
    </div>
  );
};
