import ConfigProvider from '../config-provider';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import cls from 'classnames';
import { CommonThemeProps } from '../types';
import { Search as NextSearch } from '@alifd/next';
import { SearchProps as NextSearchProps } from '@alifd/next/types/search';
import { getTheme } from '../utils/getTheme';


interface SearchProps extends Omit<NextSearchProps, 'size'|'type'>, CommonThemeProps {
  size?: 'large' | 'medium' | 'small' | 'xs';
  type?: 'normal' | 'primary' | 'secondary' | 'dark' | 'brand' ;
}

interface ISearchState {
  focus?: boolean;
}

class Search extends Component<SearchProps, ISearchState> {
  constructor(props) {
    super(props);
    this.state = {
      focus: false,
    };
  }

  onFocus = e => {
    this.setState({
      focus: true,
    });
    const { onFocus } = this.props;
    onFocus && onFocus(e);
  };

  onBlur = e => {
    this.setState({
      focus: false,
    });
    const { onBlur } = this.props;
    onBlur && onBlur(e);
  };

  // contextTypes
  static contextTypes = {
    theme: PropTypes.string,
  };

  render() {

    const { prefix = 'next-', size = 'medium', type = 'normal', shape, popupClassName, ...otherProps } = this.props;

    const theme = getTheme(this.context, this.props);

    return <NextSearch
      size={size as 'large' | 'medium'}
      {...otherProps}
      className = {cls(
        this.props.className, {
          [`${prefix}search-normal`]: shape === 'simple',
          [`${prefix}contain-focus`]: this.state.focus === true,
          [`${prefix}small`]: size === 'small',
          [`${prefix}xs`]: size === 'xs',
          [`${prefix}grey`]: theme === 'grey',
          [`${prefix}white`]: theme === 'white',
          [`${prefix}brand`]: type === 'brand',
          [`${prefix}search-with-no-title`]: !this.props.searchText,
        })}
      popupClassName={cls(popupClassName, {
        [`${prefix}white`]: theme === 'white',
        [`${prefix}grey`]: theme === 'grey',
      })}
      filterProps={{ popupClassName: cls(popupClassName, {
        [`${prefix}white`]: theme === 'white',
        [`${prefix}grey`]: theme === 'grey',
      }) }}
      onBlur={this.onBlur}
      onFocus={this.onFocus}
    />;
  }
}
export default ConfigProvider.config(Search);
