import { useState, useRef } from 'react';
import PropTypes from 'prop-types';
import { IconButton, Tooltip, TextField } from '@mui/material';
import { Search as SearchIcon, Clear as ClearIcon } from '@mui/icons-material';
import clsx from 'clsx';
import noop from 'lodash/noop';

import { useDatatableContext } from './DatatableContext';
import { styled } from '../Theme';

export default function TableSearch({
  search = '',
  options,
  searchText = '',
  searchTextUpdate,
  searchClose,
  onSearchOpen = noop,
}) {
  const { searchOpen, searchPlaceholder, searchAlwaysOpen } = options;
  const [inputExpand, setInputExpand] = useState(!!searchText || searchOpen || false);
  const [innerSearchText, setInnerSearchText] = useState(searchText);
  const inputTimer = useRef(null);
  const { loading } = useDatatableContext();

  const { searchDebounceTime } = options;

  const searchExpand = searchAlwaysOpen || inputExpand;

  const clickSearchIcon = () => {
    setInputExpand(true);
    onSearchOpen(true);
  };

  const onChange = (event) => {
    const { value } = event.currentTarget;
    if (searchDebounceTime) {
      clearTimeout(inputTimer.current);
      setInnerSearchText(value);
      inputTimer.current = setTimeout(() => {
        searchTextUpdate(value);
      }, searchDebounceTime);
    } else {
      searchTextUpdate(value);
    }
  };

  const clickClose = () => {
    setInputExpand(false);
    searchClose();
    setInnerSearchText('');
    onSearchOpen(false);
  };

  return (
    <Container
      className={clsx({
        'search-always-open': searchAlwaysOpen,
      })}>
      {searchExpand ? (
        <div className="toolbar-search-icon-placeholder">
          <SearchIcon />
        </div>
      ) : (
        <Tooltip title={search} disableFocusListener>
          <IconButton
            aria-label={search}
            data-testid={`${search}-iconButton`}
            disabled={options.search === 'disabled'}
            onClick={clickSearchIcon}>
            <SearchIcon />
          </IconButton>
        </Tooltip>
      )}

      <div className={`toolbar-search-area ${searchExpand ? 'toolbar-btn-show' : ''}`}>
        {searchExpand && !loading && (
          <TextField
            variant="standard"
            spacing={2}
            onChange={onChange}
            value={searchDebounceTime ? innerSearchText : searchText}
            placeholder={searchPlaceholder || ''}
            autoFocus={!searchAlwaysOpen}
          />
        )}
        {/* loading完成后没办法使用focus方法，所以改用两个 TextField */}
        {loading && (
          <TextField
            disabled
            variant="standard"
            spacing={2}
            value={searchDebounceTime ? innerSearchText : searchText}
          />
        )}
      </div>
      {!searchAlwaysOpen && (
        <div className={`toolbar-search-close ${searchExpand ? 'toolbar-btn-show' : ''}`}>
          <IconButton onClick={clickClose} aria-label="click to close the search box">
            <ClearIcon />
          </IconButton>
        </div>
      )}
    </Container>
  );
}

TableSearch.propTypes = {
  search: PropTypes.string,
  searchText: PropTypes.string,
  onSearchOpen: PropTypes.func,
  options: PropTypes.object.isRequired,
  searchTextUpdate: PropTypes.func.isRequired,
  searchClose: PropTypes.func.isRequired,
};

const Container = styled('div')`
  display: flex;
  align-items: center;
  .toolbar-search-area {
    width: 0;
    transition: all ease 0.3s;
    overflow: hidden;
    .MuiFormControl-root {
      width: inherit;
      margin: 0 12px;
    }
    &.toolbar-btn-show {
      width: 260px;
      padding-left: 8px;

      ${(props) => props.theme.breakpoints.down('md')} {
        width: 200px;
      }

      ${(props) => props.theme.breakpoints.down('sm')} {
        width: 180px;
      }
      &.small-textfield {
        width: 200px;
      }
    }
  }
  .toolbar-search-close {
    width: 0;
    transition: all ease 0.3s;
    overflow: hidden;
    &.toolbar-btn-show {
      width: 40px;
    }
  }
  .toolbar-search-icon-placeholder {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 40px;
    height: 40px;
  }
  &.search-always-open {
    .MuiFormControl-root {
      margin: 0 12px 0 0;
    }
    .toolbar-btn-show {
      padding-left: 0;
    }
  }
`;
