// DebouncedSearchBar.jsx
import React, { useEffect, useRef, useState } from 'react';
import { FormControl, OutlinedInput, InputAdornment, IconButton, useTheme } from '@mui/material';
import SearchOutlined from '@mui/icons-material/SearchOutlined';
import ClearIcon from '@mui/icons-material/Clear';

const SearchBar = ({ value, onChange, sx, placeholder = 'Search (Ctrl + K)', delay = 300 }) => {
  const theme = useTheme();
  const inputRef = useRef(null);

  // Local input state for immediate UI update
  const [inputValue, setInputValue] = useState(value || '');

  /* Sync external value when it changes */
  useEffect(() => {
    setInputValue(value || '');
  }, [value]);

  /* ================================
      🔥 Debounce Logic
     ================================ */
  useEffect(() => {
    const handler = setTimeout(() => {
      if (inputValue !== value) {
        onChange({ target: { value: inputValue } });
      }
    }, delay);

    return () => clearTimeout(handler);
  }, [inputValue]);

  /* CTRL + K / CMD + K & ESC behavior */
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        inputRef.current?.focus();
      }

      if (event.key === 'Escape' && document.activeElement === inputRef.current) {
        inputRef.current.blur();
      }
    };

    document.addEventListener('keydown', handleKeyPress);
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, []);

  return (
    <FormControl fullWidth>
      <OutlinedInput
        inputRef={inputRef}
        placeholder={placeholder}
        sx={{
          borderRadius: 0,
          ...sx
        }}
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)} // No direct onChange
        autoComplete="off"
        size="large"
        startAdornment={
          <InputAdornment position="start" sx={{ mr: -0.5, color: theme.palette.secondary.main }}>
            <SearchOutlined />
          </InputAdornment>
        }
        endAdornment={
          <IconButton sx={{ visibility: inputValue ? 'visible' : 'hidden' }} onClick={() => setInputValue('')}>
            <ClearIcon style={{ fontSize: 'large', color: theme.palette.primary.main }} />
          </IconButton>
        }
      />
    </FormControl>
  );
};

export default SearchBar;
