/**
 * QuickAddButton - A button that appears on node hover to quickly add successor nodes
 *
 * When clicked, shows a popup with available components that can be added as successors.
 * Selecting a component creates a new node and connects it to the source node.
 */

import React, { useState, useCallback, useMemo, useRef } from 'react';
import { FiPlus, FiZap, FiActivity, FiGitBranch } from 'react-icons/fi';
import { Component } from '../store/store';
import { t } from '../utils/translation';
import QuickAddPopup from './QuickAddPopup';
import type { QuickAddPopupConfig } from './QuickAddPopup';

interface QuickAddButtonProps {
  onAddNode: (component: Component) => void;
  disabled?: boolean;
}

const QuickAddButton: React.FC<QuickAddButtonProps> = ({
  onAddNode,
  disabled = false
}) => {
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // Handle button click - toggles popup open/closed
  const handleButtonClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    if (!disabled) {
      setIsPopupOpen(prev => !prev);
      setSelectedCategory(null);
    }
  }, [disabled]);

  // Handle popup close
  const handleClosePopup = useCallback(() => {
    setIsPopupOpen(false);
    setSelectedCategory(null);
  }, []);

  // Handle component selection
  const handleSelectComponent = useCallback((component: Component) => {
    setIsPopupOpen(false);
    setSelectedCategory(null);
    onAddNode(component);
  }, [onAddNode]);

  // Filter: exclude Events, Triggers, and Conditions (those are not successor nodes)
  const componentFilter = useCallback((components: Component[]) => {
    return components.filter(comp =>
      comp.category !== 'Events'
      && comp.category !== 'Triggers'
      && comp.category !== 'Conditions'
    );
  }, []);

  // Get icon for category
  const getCategoryIcon = useCallback((category: string) => {
    switch (category) {
      case 'Actions':
        return <FiActivity size={14} />;
      case 'Gateways':
        return <FiGitBranch size={14} />;
      default:
        return <FiZap size={14} />;
    }
  }, []);

  // Get available categories from filtered components (computed inside popup)
  // We pass a simple icon renderer for component items
  const renderComponentIcon = useCallback((component: Component) => {
    return getCategoryIcon(component.category || '');
  }, [getCategoryIcon]);

  const popupConfig: QuickAddPopupConfig = useMemo(() => ({
    title: t('Add Successor'),
    searchPlaceholder: t('Search components...'),
    searchAriaLabel: t('Search components'),
    emptyMessage: t('No components found'),
    popupWidth: 320,
    popupHeight: 400,
    componentFilter,
    renderComponentIcon,
    mergeOthersCategory: true,
  }), [componentFilter, renderComponentIcon]);

  // Category tabs - we need to compute available categories
  // This is passed to the popup via the categoryTabs prop
  const categoryTabs = useMemo(() => ({
    availableCategories: [] as string[], // Will be computed by popup via store
    selectedCategory,
    onSelectCategory: setSelectedCategory,
    renderCategoryIcon: getCategoryIcon,
  }), [selectedCategory, getCategoryIcon]);

  if (disabled) {
    return null;
  }

  return (
    <>
      <button
        ref={buttonRef}
        className="quick-add-button"
        onClick={handleButtonClick}
        title={t('Add successor node')}
        aria-label={t('Add successor node')}
      >
        <FiPlus size={14} />
      </button>

      <QuickAddPopup
        isOpen={isPopupOpen}
        onClose={handleClosePopup}
        onSelect={handleSelectComponent}
        config={popupConfig}
        buttonRef={buttonRef}
        categoryTabs={categoryTabs}
      />
    </>
  );
};

export default QuickAddButton;
