import React, { useState, useRef, useEffect, useCallback } from "react";
import MenuItem from "@mui/material/MenuItem";
import SearchIcon from "../../assets/searchIconTable.svg";
import "./MenuHeaderInfo.styles.scss";
import { Checkbox } from "../Checkbox";
import { RadioButtonGroup } from "../RadioButtonGroup";
import { chartConfig } from "../TableChat/components/chatConfig";

const MenuOptionsHeaderComponent = ({
  options,
  selectedItems,
  onSearchChange,
  onSelectAll,
  searchQuery,
  onClearSelection,
  onRadioButtonChange,
  radioButtonOptions = chartConfig.userConfig.radioButtonConfig.options,
  selectedRadioButton,
  showRadioButton = chartConfig.userConfig.radioButtonConfig.showRadioButton,
  isSearchable = chartConfig.userConfig.isSearchable,
  isSelectAllAllowed = chartConfig.userConfig.showSelectAll,
  // External handlers and props for customization
  customHeaderProps = {},
  externalHandlers = {},
  overrideConfig = {},
}) => {
  // Apply external configuration overrides
  const config = {
    radioButtonOptions: overrideConfig.radioButtonOptions || radioButtonOptions,
    selectedRadioButton: overrideConfig.selectedRadioButton,
    showRadioButton:
      overrideConfig.showRadioButton !== undefined
        ? overrideConfig.showRadioButton
        : showRadioButton,
    isSearchable:
      overrideConfig.isSearchable !== undefined
        ? overrideConfig.isSearchable
        : isSearchable,
    isSelectAllAllowed:
      overrideConfig.isSelectAllAllowed !== undefined
        ? overrideConfig.isSelectAllAllowed
        : isSelectAllAllowed,
  };

  const [selectedRadioOption, setSelectedRadioOption] = useState(
    config.selectedRadioButton || ""
  );
  const [internalSearchQuery, setInternalSearchQuery] = useState(searchQuery);

  // Ref to maintain focus during re-renders
  const inputRef = useRef(null);
  const isUserTyping = useRef(false);

  // Maintain focus only when user is actively typing
  useEffect(() => {
    if (
      isUserTyping.current &&
      inputRef.current &&
      document.activeElement !== inputRef.current
    ) {
      inputRef.current.focus();
    }
  });

  useEffect(() => {
    if (!searchQuery) {
      setInternalSearchQuery("");
    }
  }, [searchQuery]);

  // Debounced external handler to prevent excessive re-renders
  const debouncedExternalHandler = useCallback(
    debounce((value) => {
      if (externalHandlers.onSearchChange) {
        externalHandlers.onSearchChange(value);
      } else if (onSearchChange) {
        onSearchChange(value);
      }
    }, 500),
    [externalHandlers.onSearchChange, onSearchChange]
  );

  const handleSearchChange = (event) => {
    const value = event.target.value;

    // Mark that user is actively typing
    isUserTyping.current = true;

    setInternalSearchQuery(value);

    // Call external handlers with debounce to prevent excessive re-renders
    debouncedExternalHandler(value);

    // Reset typing flag after a delay
    setTimeout(() => {
      isUserTyping.current = false;
    }, 50);
  };

  // Simple debounce utility
  function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        clearTimeout(timeout);
        func(...args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  }

  const handleKeyDown = (event) => {
    // Allow clipboard operations (copy, paste, cut, select all)
    if (event.ctrlKey || event.metaKey) {
      const allowedKeys = ["c", "v", "x", "a", "z", "y"]; // copy, paste, cut, select all, undo, redo
      if (allowedKeys.includes(event.key.toLowerCase())) {
        // Stop propagation but allow default behavior for clipboard operations
        event.stopPropagation();
        if (event.nativeEvent && event.nativeEvent.stopImmediatePropagation) {
          event.nativeEvent.stopImmediatePropagation();
        }
        isUserTyping.current = true;
        return; // Don't prevent default for clipboard operations
      }
    }

    // Allow arrow keys and other navigation/utility keys
    const navigationKeys = [
      "ArrowLeft",
      "ArrowRight",
      "ArrowUp",
      "ArrowDown",
      "Home",
      "End",
      "PageUp",
      "PageDown",
      "Tab",
      "Escape",
      "Enter",
    ];
    if (navigationKeys.includes(event.key)) {
      event.stopPropagation();
      if (event.nativeEvent && event.nativeEvent.stopImmediatePropagation) {
        event.nativeEvent.stopImmediatePropagation();
      }
      return; // Don't prevent default for navigation
    }

    // Prevent the Menu component from capturing keyboard events
    event.stopPropagation();
    event.preventDefault();

    // Use native event for immediate propagation stopping if available
    if (event.nativeEvent && event.nativeEvent.stopImmediatePropagation) {
      event.nativeEvent.stopImmediatePropagation();
    }

    // Mark that user is actively typing
    isUserTyping.current = true;

    // Manually handle input for problematic keys
    if (
      event.key.length === 1 ||
      event.key === "Backspace" ||
      event.key === "Delete"
    ) {
      const input = event.target;
      const start = input.selectionStart;
      const end = input.selectionEnd;
      const currentValue = input.value;
      let newValue;
      let newCursorPos;

      if (event.key === "Backspace") {
        if (start === end && start > 0) {
          newValue =
            currentValue.slice(0, start - 1) + currentValue.slice(start);
          newCursorPos = start - 1;
        } else if (start !== end) {
          newValue = currentValue.slice(0, start) + currentValue.slice(end);
          newCursorPos = start;
        } else {
          return; // Nothing to delete
        }
      } else if (event.key === "Delete") {
        if (start === end && start < currentValue.length) {
          newValue =
            currentValue.slice(0, start) + currentValue.slice(start + 1);
          newCursorPos = start;
        } else if (start !== end) {
          newValue = currentValue.slice(0, start) + currentValue.slice(end);
          newCursorPos = start;
        } else {
          return; // Nothing to delete
        }
      } else if (event.key.length === 1) {
        newValue =
          currentValue.slice(0, start) + event.key + currentValue.slice(end);
        newCursorPos = start + 1;
      }

      if (newValue !== undefined) {
        setInternalSearchQuery(newValue);
        debouncedExternalHandler(newValue);

        // Update cursor position
        setTimeout(() => {
          if (input && newCursorPos !== undefined) {
            input.setSelectionRange(newCursorPos, newCursorPos);
          }
        }, 0);
      }
    }
  };
  const isAllSelected =
    selectedItems.length === options.length && options.length > 0;
  const isIndeterminate =
    selectedItems.length > 0 && selectedItems.length < options.length;

  const onSelectRadioButton = (event) => {
    setSelectedRadioOption(event.target.value);
    // Call external handler if provided, otherwise use default
    if (externalHandlers.onRadioButtonChange) {
      externalHandlers.onRadioButtonChange(event.target.value);
    } else if (onRadioButtonChange) {
      onRadioButtonChange(event.target.value);
    }
  };

  const handleSelectAll = () => {
    // Extract values from options for selection
    const allValues = options?.map((opt) => opt.value) || [];

    if (externalHandlers.onSelectAll) {
      externalHandlers.onSelectAll(allValues);
    } else if (onSelectAll) {
      onSelectAll(allValues);
    }
  };

  const handleClearSelection = () => {
    if (externalHandlers.onClearSelection) {
      externalHandlers.onClearSelection();
    } else if (onClearSelection) {
      onClearSelection();
    }
  };

  return (
    <div className="menu-header menu-header-fixed" {...customHeaderProps}>
      {config.showRadioButton ? (
        <div className="menu-header-radio-group-container">
          <RadioButtonGroup
            name="menu-header-radio-group"
            onChange={onSelectRadioButton}
            options={config.radioButtonOptions}
            selectedOption={selectedRadioOption}
            orientation="row"
            {...(customHeaderProps.radioButtonProps || {})}
          />
        </div>
      ) : null}

      {config.isSearchable ? (
        <div
          className="menu-header-search-container"
          role="search"
          aria-label="Search input container"
        >
          <img
            src={SearchIcon}
            alt="search"
            className="menu-header-search-icon"
          />
          <input
            ref={inputRef}
            placeholder={
              customHeaderProps.searchPlaceholder || "Search here..."
            }
            className="menu-header-search-input"
            type="text"
            value={internalSearchQuery}
            onChange={handleSearchChange}
            onKeyDown={handleKeyDown}
            autoComplete="off"
            tabIndex={0}
            {...(customHeaderProps.searchInputProps || {})}
          />
        </div>
      ) : null}

      {config.isSelectAllAllowed ? (
        <MenuItem className="select-all-option">
          <div className="ia-menu-checkbox">
            <Checkbox
              variant="default"
              label={customHeaderProps.selectAllLabel || "Select all"}
              checked={isAllSelected}
              indeterminate={isIndeterminate}
              onChange={handleSelectAll}
              {...(customHeaderProps.checkboxProps || {})}
            />
          </div>
          <span
            className="clear-text"
            onClick={handleClearSelection}
            {...(customHeaderProps.clearButtonProps || {})}
          >
            {customHeaderProps.clearButtonText || "Clear"}
          </span>
        </MenuItem>
      ) : null}
    </div>
  );
};

// Export memoized component to prevent unnecessary re-renders
export const MenuOptionsHeader = React.memo(MenuOptionsHeaderComponent);
