/* eslint-disable react/prop-types */
import React, { useEffect, useRef } from 'react';
import { OutlinedInput, InputAdornment, Tooltip, IconButton } from '@mui/material';
import { SearchOutlined } from '@mui/icons-material';
import ClearIcon from '@mui/icons-material/Clear';
import { useDebounce } from 'use-debounce';

const DebounceSearchBar = ({
  value,
  onChange,
  onDebouncedChange, // 🔹 NEW
  debounceTime = 500,
  placeholder = 'Search (ctrl+k)',
  sx
}) => {
  const textFieldRef = useRef(null);

  const [debouncedValue] = useDebounce(value, debounceTime);

  // fire debounced callback whenever debouncedValue changes
  useEffect(() => {
    if (onDebouncedChange) {
      onDebouncedChange(debouncedValue);
    }
  }, [debouncedValue, onDebouncedChange]);

  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        textFieldRef.current?.focus();
      }
      if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
        textFieldRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, []);

  return (
    <OutlinedInput
      sx={{ ...sx }}
      inputRef={textFieldRef}
      placeholder={placeholder}
      autoComplete="off"
      value={value}
      fullWidth
      onChange={(e) => onChange(e.target.value)}
      startAdornment={
        <InputAdornment position="start" sx={{ mr: -0.5 }}>
          <SearchOutlined />
        </InputAdornment>
      }
      endAdornment={
        <Tooltip title="Clear">
          <IconButton sx={{ visibility: value ? 'visible' : 'hidden' }} onClick={() => onChange('')}>
            <ClearIcon />
          </IconButton>
        </Tooltip>
      }
    />
  );
};

export default DebounceSearchBar;
