import React, { useState, useRef, useEffect, useCallback } from "react";
import ToggleButton from "./ToggleButton";

export default function FilterInput({ label, color, bgColor, value, onChange, columns, columnsOnly = false, plainText = false, highlightOptions, onHighlightOptionToggle }) {
  const [showDropdown, setShowDropdown] = useState(false);
  const [activeIndex, setActiveIndex] = useState(0);
  const [filteredCols, setFilteredCols] = useState([]);
  const inputRef = useRef(null);
  const dropdownRef = useRef(null);

  const getActiveSegment = useCallback(() => {
    const input = inputRef.current;
    if (!input) return { text: "", start: 0, end: 0 };
    const cursor = input.selectionStart || 0;
    const val = input.value;
    let start = val.lastIndexOf(",", cursor - 1) + 1;
    let end = val.indexOf(",", cursor);
    if (end === -1) end = val.length;
    const segment = val.slice(start, end).trimStart();
    const trimOffset = val.slice(start, end).length - val.slice(start, end).trimStart().length;
    return { text: segment, start: start + trimOffset, end };
  }, []);

  const updateDropdown = useCallback(() => {
    const { text } = getActiveSegment();
    if (!columnsOnly && text.includes(":")) {
      setShowDropdown(false);
      return;
    }
    const query = text.toLowerCase();
    const matches = columns.filter((c) => !query || c.name.toLowerCase().includes(query));
    setFilteredCols(matches);
    setActiveIndex(0);
    setShowDropdown(matches.length > 0 && document.activeElement === inputRef.current);
  }, [columns, columnsOnly, getActiveSegment]);

  const insertColumn = useCallback(
    (colName) => {
      const input = inputRef.current;
      if (!input) return;
      const { start, end } = getActiveSegment();
      const val = input.value;
      const before = val.slice(0, start);
      const after = val.slice(end);
      const insertion = columnsOnly ? colName + ", " : colName + ":";
      const newVal = before + insertion + after;
      onChange(newVal);
      setShowDropdown(false);
      requestAnimationFrame(() => {
        const pos = start + insertion.length;
        input.setSelectionRange(pos, pos);
        input.focus();
      });
    },
    [columnsOnly, getActiveSegment, onChange]
  );

  const handleKeyDown = (e) => {
    if (!showDropdown) return;
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setActiveIndex((i) => Math.min(i + 1, filteredCols.length - 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setActiveIndex((i) => Math.max(i - 1, 0));
    } else if (e.key === "Tab" || e.key === "Enter") {
      if (filteredCols.length > 0) {
        e.preventDefault();
        insertColumn(filteredCols[activeIndex].name);
      }
    } else if (e.key === "Escape") {
      setShowDropdown(false);
    }
  };

  const handleInput = (e) => {
    onChange(e.target.value);
    if (!plainText) {
      requestAnimationFrame(updateDropdown);
    }
  };

  useEffect(() => {
    const handleClick = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target) && e.target !== inputRef.current) {
        setShowDropdown(false);
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  useEffect(() => {
    if (showDropdown && dropdownRef.current) {
      const item = dropdownRef.current.children[activeIndex];
      if (item) item.scrollIntoView({ block: "nearest" });
    }
  }, [activeIndex, showDropdown]);

  return (
    <div style={{ position: "relative", flex: 1, minWidth: 200 }}>
      <label
        style={{
          display: "block",
          fontSize: 10,
          fontWeight: 600,
          textTransform: "uppercase",
          letterSpacing: "0.1em",
          color: color,
          marginBottom: 4,
        }}
      >
        {label}
      </label>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          background: bgColor,
          border: `1px solid ${color}33`,
          borderRadius: 6,
          transition: "border-color 0.15s",
        }}
      >
        <input
          ref={inputRef}
          type="text"
          value={value}
          onChange={handleInput}
          onFocus={plainText ? undefined : updateDropdown}
          onKeyDown={plainText ? undefined : handleKeyDown}
          placeholder={`${label.toLowerCase()}...`}
          spellCheck={false}
          style={{
            flex: 1,
            background: "transparent",
            border: "none",
            padding: "8px 12px",
            color: "var(--text)",
            fontFamily: "inherit",
            fontSize: 13,
            outline: "none",
            minWidth: 0,
          }}
          onFocusCapture={(e) => { e.target.closest("div").style.borderColor = color + "66"; }}
          onBlurCapture={(e) => {
            e.target.closest("div").style.borderColor = color + "33";
            setTimeout(() => setShowDropdown(false), 150);
          }}
        />
        {highlightOptions && (
          <div style={{ display: "flex", gap: 2, paddingRight: 6, flexShrink: 0 }}>
            <ToggleButton label="Aa" active={highlightOptions.caseSensitive} onClick={() => onHighlightOptionToggle("caseSensitive")} color={color} />
            <ToggleButton label="ab" active={highlightOptions.wholeWord} onClick={() => onHighlightOptionToggle("wholeWord")} color={color} />
            <ToggleButton label=".*" active={highlightOptions.regex} onClick={() => onHighlightOptionToggle("regex")} color={color} />
          </div>
        )}
      </div>
      {showDropdown && filteredCols.length > 0 && (
        <div
          ref={dropdownRef}
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            right: 0,
            marginTop: 4,
            background: "var(--panel)",
            border: "1px solid var(--border)",
            borderRadius: 6,
            maxHeight: 200,
            overflowY: "auto",
            zIndex: 100,
            boxShadow: "0 8px 24px rgba(0,0,0,0.4)",
          }}
        >
          {filteredCols.map((col, i) => (
            <div
              key={col.name}
              onMouseDown={(e) => { e.preventDefault(); insertColumn(col.name); }}
              style={{
                padding: "6px 12px",
                cursor: "pointer",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                background: i === activeIndex ? "rgba(255,255,255,0.05)" : "transparent",
              }}
            >
              <span style={{ color: "var(--text)" }}>{col.name}</span>
              <span style={{ color: "var(--text-dim)", fontSize: 11 }}>{col.type}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
