/* global wp */
/**
 * Command Palette Component
 *
 * Provides global command palette for quick navigation and actions
 * Triggered by Cmd/Ctrl+K keyboard shortcut
 *
 * @package
 */

import { __ } from '@wordpress/i18n';
import { useState, useEffect, useCallback, useRef } from '@wordpress/element';
import { Modal, TextControl } from '@wordpress/components';
/* eslint-disable @wordpress/no-unsafe-wp-apis */
import { useKeyboardShortcut } from '@wordpress/compose';
import apiFetch from '@wordpress/api-fetch';
import Fuse from 'fuse.js';

const CommandPalette = () => {
  // State management
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [items, setItems] = useState([]);
  const [filteredItems, setFilteredItems] = useState([]);
  const [selectedIndex, setSelectedIndex] = useState(0);

  // Refs
  const searchInputRef = useRef(null);
  const fuseRef = useRef(null);

  const isTypingTarget = useCallback((event) => {
    const target = event?.target || document.activeElement;
    if (!target) {
      return false;
    }

    const tag = target.tagName ? target.tagName.toLowerCase() : '';
    return (
      target.isContentEditable === true ||
      tag === 'input' ||
      tag === 'textarea' ||
      tag === 'select'
    );
  }, []);

  // Keyboard shortcut registration
  useKeyboardShortcut(
    'primary+k',
    (event) => {
      if (isTypingTarget(event)) {
        return;
      }
      event.preventDefault();
      setIsOpen(true);
    },
    {
      bindGlobal: true,
      target: document,
    }
  );

  // Fetch command palette items
  const fetchItems = useCallback(async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/command-palette/items',
        method: 'GET',
      });

      if (
        response &&
        typeof response === 'object' &&
        response.success === true &&
        response.data !== undefined &&
        response.data !== null &&
        typeof response.data === 'object' &&
        Array.isArray(response.data.items)
      ) {
        setItems(response.data.items);
        // Initialize Fuse.js for fuzzy search
        fuseRef.current = new Fuse(response.data.items, {
          keys: ['label', 'description'],
          threshold: 0.3,
          includeScore: true,
        });
      }
      // If error UI is wanted, add here
    } catch (err) {
      // If error UI is wanted, add here
    }
  }, []);

  // Fetch items when modal opens
  useEffect(() => {
    if (isOpen === true && Array.isArray(items) && items.length === 0) {
      fetchItems();
    }
  }, [isOpen, items, fetchItems]);

  // Focus search input when modal opens
  useEffect(() => {
    if (isOpen === true) {
      setTimeout(() => {
        searchInputRef.current.focus();
      }, 100);
    }
  }, [isOpen]);

  // Filter items based on search query
  useEffect(() => {
    if (typeof searchQuery === 'string' && searchQuery.trim().length === 0) {
      setFilteredItems(items);
      setSelectedIndex(0);
      return;
    }

    if (fuseRef.current !== undefined && fuseRef.current !== null) {
      const results = fuseRef.current.search(searchQuery);
      setFilteredItems(results.map((result) => result.item));
      setSelectedIndex(0);
    }
  }, [searchQuery, items]);

  // Handle modal close
  const handleClose = useCallback(() => {
    setIsOpen(false);
    setSearchQuery('');
    setSelectedIndex(0);
  }, []);

  if (isOpen !== true) {
    return null;
  }

  return (
    <>
      <Modal
        title={__('Command Palette', 'prorank-seo')}
        onRequestClose={handleClose}
        className="prorank-command-palette__modal"
        overlayClassName="prorank-command-palette__overlay"
        shouldCloseOnClickOutside={true}
        shouldCloseOnEsc={true}
        isDismissible={true}
        focusOnMount={false}
        headerActions={null}
      >
        <div
          className="prorank-command-palette"
          role="application"
          aria-label={__('Command palette navigation', 'prorank-seo')}
        >
          <div className="prorank-command-palette__search">
            <TextControl
              ref={searchInputRef}
              value={searchQuery}
              onChange={setSearchQuery}
              placeholder={__('Type to search', 'prorank-seo')}
              className="prorank-command-palette__input"
              hideLabelFromVision={true}
              label={__('Search commands', 'prorank-seo')}
              autoComplete="off"
              role="combobox"
              aria-expanded="true"
              aria-controls="prorank-command-palette-results"
              aria-autocomplete="list"
              aria-activedescendant={
                filteredItems[selectedIndex] ? `prorank-command-item-${selectedIndex}` : undefined
              }
            />
          </div>
          {/* Add the rest of your modal JSX here, or close the modal if this is the end. */}
        </div>
      </Modal>
    </>
  );
};

export default CommandPalette;
