import React, { useState } from 'react';
import PT from 'prop-types';
import { useRouter } from 'next/router';
import { SearchRounded } from '@mui/icons-material';

import { getDemandTagLink, getSupplyTagLink } from '@/modules/marketplace/common/helpers/supplyDemandTransitionLinks';

import { Autocomplete, TextField, Typography } from '@/mui/components';

import styles from './SearchNew.module.scss';

const GROUP_TYPES = {
  supply: 'Supply',
  demand: 'Demand',
};

function Search(props) {
  const router = useRouter();
  const [searchText, setSearchText] = useState('');
  const handleSearch = (text) => {
    props.setSearchAction({
      search: text,
    });
    setSearchText(text);
  };
  const handleTransition = (tag) => {
    const links = {
      [GROUP_TYPES.supply]: getSupplyTagLink(tag),
      [GROUP_TYPES.demand]: getDemandTagLink(tag),
    };
    const link = links[tag.groupName];

    if (router.pathname !== link.substr(0, link.indexOf('?'))) {
      router.push(link);
    }
  };

  return (
    <div className={styles.Wrapper}>
      <Autocomplete
        id="global-search"
        classes={{
          popupIndicatorOpen: styles.AutocompleteOverride___popupIndicatorOpen,
          groupLabel: styles.AutocompleteOverride___groupLabel,
          groupUl: styles.AutocompleteOverride___groupUl,
        }}
        options={props.searchResult}
        groupBy={(option) => option.groupName}
        optionValueKey="id"
        getOptionLabel={(option) => `${option.name} (${option.id})`}
        renderOption={(optionsProps, option) => (
          <span className={option.status !== 'ACTIVE' ? styles.InActiveOption : ''} {...optionsProps}>
            {`${option.name} (${option.id})`}
          </span>
        )}
        disableClearable
        onChange={(e, data = {}) => handleTransition(data)}
        onInputChange={(e, data) => handleSearch(data)}
        size="small"
        popupIcon={<SearchRounded />}
        noOptionsText={
          <Typography variant="caption">
            {searchText.length <= 1 ? 'Type at least 2 symbols for search' : ''}
            {props.isLoading && searchText.length > 1 ? 'Loading...' : ''}
            {searchText.length > 1 && !props.searchResult.length && !props.isLoading ? 'Not found tags' : ''}
          </Typography>
        }
        renderInput={(params) => (
          <TextField
            {...params}
            data-id="search-input"
            placeholder="Search for Supply & Demand tags"
            variant="outlined"
          />
        )}
      />
    </div>
  );
}

Search.propTypes = {
  searchResult: PT.arrayOf(
    PT.shape({
      id: PT.string,
    }),
  ).isRequired,
  setSearchAction: PT.func.isRequired,
  isLoading: PT.bool.isRequired,
};

export default Search;
