import React, { useState, useRef, useEffect, useCallback } from "react";
import { SearchIcon } from "../../../assets/svg";
import useOutsideClick from "../../libs/hooks/useOutsideClick";
import { customDebounce } from "../../libs/utils/debounce";
import { Box, IconButton, InputAdornment, TextField } from "@mui/material";
import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
import { searchStyles } from "./style";

interface TableSearchProps {
  value: string;
  onChange: (value: string) => void;
}

export const TableSearch = ({
  value,
  onChange,
}: TableSearchProps): JSX.Element => {
  const [showSearchInput, setShowSearchInput] = useState(false);
  const [localValue, setLocalValue] = useState(value);
  const searchContainerRef = useRef<HTMLDivElement>(null);

  // Debounced onChange function
  const debouncedOnChange = useCallback(
    customDebounce((newValue: string) => {
      onChange(newValue);
    }, 1000),
    [onChange]
  );

  // Sync local state with prop value
  useEffect(() => {
    setLocalValue(value);
  }, [value]);

  useOutsideClick({
    ref: searchContainerRef,
    handler: () => {
      setShowSearchInput(false);
    },
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    setLocalValue(newValue);
    debouncedOnChange(newValue);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      onChange(localValue);
    }
    if (e.key === "Escape") {
      setShowSearchInput(false);
    }
  };

  return (
    <Box
      ref={searchContainerRef}
      className="search-container"
      sx={{ position: "relative" }}
    >
      <TextField
        type="text"
        placeholder="Search"
        value={localValue}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        className={`search-input ${showSearchInput ? "expanded" : ""}`}
        sx={searchStyles.searchField(showSearchInput)}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <IconButton
                size="small"
                onClick={() => {
                  setShowSearchInput((prev) => !prev);
                  if (!showSearchInput) {
                    setTimeout(() => {
                      searchContainerRef.current
                        ?.querySelector("input")
                        ?.focus();
                    }, 100);
                  }
                }}
                sx={{ color: "black", fontSize: 14 }}
                edge="start"
              >
                <SearchIcon />
              </IconButton>
            </InputAdornment>
          ),
          endAdornment:
            showSearchInput && localValue !== "" ? (
              <InputAdornment position="end">
                <IconButton
                  size="small"
                  onClick={() => {
                    setLocalValue("");
                    handleChange({ target: { value: "" } } as any);
                  }}
                  sx={{ color: "black", fontSize: 14 }}
                  edge="end"
                >
                  <CloseRoundedIcon
                    fontSize="small"
                    sx={{ color: "black", fontSize: 14 }}
                  />
                </IconButton>
              </InputAdornment>
            ) : null,
        }}
      />
    </Box>
  );
};
