import React, { useEffect, useState, useRef } from 'react';
import { IconButton, InputBase, Paper, List, ListItem, ListItemText, Popper, ClickAwayListener } from '@mui/material';
import { Clear as ClearIcon, Search as SearchIcon } from '@mui/icons-material';
import debounce from 'lodash.debounce';
import PropTypes from 'prop-types';
import useApiService from '../services/apiService.js';
import { smartSearch } from '../constants/apiEndPoints.js';

function SearchInput({ onSearch, onClear, textToSearch = '', changeHandler = () => {}, placeholder = '' }) {
  const { getApi } = useApiService();
  const [searchText, setSearchText] = useState("");
  const [suggestions, setSuggestions] = useState([]);
  const [openSuggestions, setOpenSuggestions] = useState(false);
  const anchorRef = useRef(null);

  useEffect(() => {
    setSearchText(textToSearch);
  }, [textToSearch]);

  const debouncedFetch = useRef(
    debounce(async (query) => {
      if (query.trim().length >= 3) {
        const result = await fetchSuggestions(query); 
        setSuggestions(result || []);
        setOpenSuggestions(true);
      } else {
        setSuggestions([]);
        setOpenSuggestions(false);
      }
    }, 300)
  ).current;

  const handleInputChange = (e) => {
    const {value} = e.target;
    if (placeholder === "Activity Reports") {
      changeHandler(value);
    }
    setSearchText(value);
    debouncedFetch(value);
  };

  const handleItemSelect = (item) => {
    setSearchText(`${item.EmpName} - ${item.EmpCode}`);
    setOpenSuggestions(false);
    setSuggestions([]);
    onSearch(item.EmpCode || item.EmpName);
  };

  const handleClear = () => {
    setSearchText("");
    setSuggestions([]);
    setOpenSuggestions(false);
    onSearch("");
    onClear();
  };

  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      if (searchText.trim().length >= 3) {
        setOpenSuggestions(false);
        onSearch(searchText);
      }
    // } else if (event.key === 'Backspace' && searchText?.length === 1) {
    //   onClear(searchText);
    // }
    }

  };

  const fetchSuggestions = async (query) => {
    const response = await getApi(`${smartSearch}?EmpCode=${query}`);
    return response;
  };

  return (
    <ClickAwayListener onClickAway={() => setOpenSuggestions(false)}>
      <div>
        <Paper
          component="form"
          sx={{
            display: 'flex',
            alignItems: 'center',
            width: 300,
            padding: '2px 4px',
            height: '40px',
            border: '1px solid #c4c4c4',
            boxShadow: 'none',
            position: 'relative',
          }}
          onSubmit={(e) => e.preventDefault()}
          ref={anchorRef}
        >
          <InputBase
            sx={{ ml: 1, flex: 1 }}
            placeholder="Enter Emp Name/ID"
            value={searchText}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            onBlur={() => {
              setTimeout(() => {
                if (searchText.trim().length >= 3 && !openSuggestions) {
                  onSearch(searchText.trim());
                }
              }, 200); // delay to allow item click
            }}
            data-testid="search-input-field"
          />
          <IconButton
            type="button"
            sx={{ p: '5px' }}
            aria-label="search"
            onClick={() => {
              if (searchText.trim().length >= 3) {
                onSearch(searchText.trim());
              }
            }}
            data-testid="search-button"
          >
            <SearchIcon />
          </IconButton>
          {searchText && (
            <IconButton
              type="button"
              sx={{ p: '5px' }}
              aria-label="clear"
              onClick={handleClear}
              data-testid="search-clear-button"
            >
              <ClearIcon />
            </IconButton>
          )}
        </Paper>

        <Popper open={openSuggestions} anchorEl={anchorRef.current} className="search-list" style={{ zIndex: 9999, width: anchorRef.current?.offsetWidth }}>
          <Paper elevation={2}>
            <List dense>
              {suggestions.map((item) => (
                <ListItem key={item.EmpCode} onClick={() => handleItemSelect(item)}>
                  <ListItemText primary={`${item.EmpName} - ${item.EmpCode}`} />
                </ListItem>
              ))}
              { !suggestions.length && (
                <span style={{padding: "2px 10px" }}>No data found</span>
              )}
            </List>
          </Paper>
        </Popper>
      </div>
    </ClickAwayListener>
  );
}

SearchInput.propTypes = {
  onSearch: PropTypes.func.isRequired,
  onClear: PropTypes.func.isRequired,
  textToSearch: PropTypes.string,
  changeHandler: PropTypes.func,
  placeholder: PropTypes.string,
};

export default SearchInput;
