import React from 'react';
import { bool, string, func } from 'prop-types';
import styled from 'styled-components';
import { Field, reduxForm } from 'redux-form';
import { REM_UNIT_XSM, REM_UNIT_SM, SONIC_SILVER, GRAY_X11 } from '@vincent_za/styles';
import { searchSvg } from '@vincent_za/assets';
import { TextField } from '../../form';
import Svg from '../../Svg/component';
import { PageSectionActionWrap } from '../component';

export const CLASSNAME_SEARCH_ICON = 'field';

const FieldLabel = styled.label``;

const SearchSvg = styled(Svg)`
  display: block;
  width: 1.4rem;
  height: 1.4rem;

  svg {
    fill: ${props => props.isOpen ? GRAY_X11 : SONIC_SILVER};

    &:hover {
      fill: ${GRAY_X11};
    };
  };
`;

const FieldWrap = styled.div`
  display: ${props => props.isOpen ? 'flex' : 'none'};
  margin-right: ${REM_UNIT_SM};
`;

const TextFieldStyled = styled(TextField)`
  padding: 0 !important;
  padding-bottom: ${REM_UNIT_XSM} !important;
  width: 10.4rem;
  height: 1.5rem;
  color: ${GRAY_X11};
  background-color: transparent;
`;

class TableSearch extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isOpen: false,
    };
  }

  componentWillUnmount() {
    this.props.onSearchReset({ searchQuery: '' });
  }

  onSearchToggle = () => {
    this.setState({
      isOpen: !this.state.isOpen,
    });
  }

  render() {
    const { isOpen } = this.state;
    const { isVisible, fieldName, handleChange, className } = this.props;

    return (
      <PageSectionActionWrap isVisible={isVisible} onChange={handleChange} className={className}>
        <FieldWrap isOpen={isOpen}>
          <Field name={fieldName} component={TextFieldStyled} id={fieldName} />
        </FieldWrap>
        <FieldLabel htmlFor={fieldName} onClick={this.onSearchToggle}>
          <SearchSvg svg={searchSvg} isOpen={isOpen} className={CLASSNAME_SEARCH_ICON} />
        </FieldLabel>
      </PageSectionActionWrap>
    );
  }
}

TableSearch.propTypes = {
  isVisible: bool,
  fieldName: string.isRequired,
  onSearchReset: func,
  handleChange: func,
  className: string,
};

TableSearch.defaultProps = {
  isVisible: true,
  onSearchReset() {},
  handleChange() {},
  className: undefined,
};

export default reduxForm()(TableSearch);
