import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import ComponentPanel from '../ComponentPanel';

jest.mock('react-icons/fi', () => ({
  FiSearch: () => <span data-testid="fi-search" />,
  FiZap: () => <span data-testid="fi-zap" />,
  FiActivity: () => <span data-testid="fi-activity" />,
  FiHelpCircle: () => <span data-testid="fi-help" />,
  FiGitBranch: () => <span data-testid="fi-git-branch" />,
  FiInfo: () => <span data-testid="fi-info" />,
  FiFilter: () => <span data-testid="fi-filter" />,
  FiChevronDown: () => <span data-testid="fi-chevron-down" />,
  FiChevronRight: () => <span data-testid="fi-chevron-right" />,
  FiChevronLeft: () => <span data-testid="fi-chevron-left" />,
  FiLink: () => <span data-testid="fi-link" />,
  FiCpu: () => <span data-testid="fi-cpu" />,
  FiLayers: () => <span data-testid="fi-layers" />,
  FiStar: () => <span data-testid="fi-star" />,
}));

jest.mock('../DocumentationButton', () => () => null);

const mockComponents = [
  { plugin: 'test.event.content', label: 'Content Insert', category: 'Events', description: 'Fires on content insert', provider: 'test_provider' },
  { plugin: 'test.action.set_value', label: 'Set Value', category: 'Actions', description: 'Sets a value', provider: 'test_provider' },
  { plugin: 'test.condition.check', label: 'Check Value', category: 'Conditions', description: 'Checks a condition', provider: 'test_provider' },
];

jest.mock('../../store/store', () => ({
  useStore: jest.fn((selector) => {
    if (typeof selector === 'function') {
      const state = {
        components: mockComponents,
        favoriteComponents: [],
        componentPanelWidth: 280,
        componentPanelIsResizing: false,
        setComponentPanelWidth: jest.fn(),
        setComponentPanelResizing: jest.fn(),
        componentPanelCollapsed: false,
        toggleComponentPanelCollapse: jest.fn(),
      };
      return selector(state);
    }
    return {};
  }),
}));

describe('ComponentPanel', () => {
  const defaultProps = {
    onComponentDrag: jest.fn(),
    onComponentDragEnd: jest.fn(),
    onConditionDragStart: jest.fn(),
    onConditionDragEnd: jest.fn(),
    onComponentDragStart: jest.fn(),
  };

  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('rendering', () => {
    it('should render the component panel', () => {
      const { container } = render(<ComponentPanel {...defaultProps} />);
      expect(container.querySelector('.workflow-component-panel')).toBeTruthy();
    });

    it('should render search input', () => {
      render(<ComponentPanel {...defaultProps} />);
      // When a type is auto-selected, placeholder shows "Search <type>..."
      const searchInput = document.querySelector('input[type="text"]');
      expect(searchInput).toBeTruthy();
      expect(searchInput?.getAttribute('placeholder')).toMatch(/Search \w+\.\.\./);
    });

    it('should render components by category', () => {
      render(<ComponentPanel {...defaultProps} />);
      // Category type selector buttons are rendered
      expect(screen.getByText('Events')).toBeTruthy();
      expect(screen.getByText('Actions')).toBeTruthy();
      expect(screen.getByText('Conditions')).toBeTruthy();
    });
  });

  describe('search', () => {
    it('should filter components by search term', () => {
      render(<ComponentPanel {...defaultProps} />);
      // Click on "Events" type to ensure it's selected, then search within it
      fireEvent.click(screen.getByText('Events'));
      const searchInput = document.querySelector('input[type="text"]') as HTMLInputElement;
      fireEvent.change(searchInput, { target: { value: 'Content' } });
      expect(screen.getByText('Content Insert')).toBeTruthy();
    });

    it('should show all components when search is empty', () => {
      render(<ComponentPanel {...defaultProps} />);
      // Click on "Events" type - only shows events
      fireEvent.click(screen.getByText('Events'));
      const searchInput = document.querySelector('input[type="text"]') as HTMLInputElement;
      fireEvent.change(searchInput, { target: { value: '' } });
      expect(screen.getByText('Content Insert')).toBeTruthy();
    });
  });

  describe('drag events', () => {
    it('should call onComponentDragStart when component is dragged', () => {
      render(<ComponentPanel {...defaultProps} />);
      // Find a component item and trigger drag with dataTransfer mock
      const components = document.querySelectorAll('.component-item');
      if (components.length > 0) {
        const dataTransfer = {
          setData: jest.fn(),
          effectAllowed: '',
        };
        fireEvent.dragStart(components[0], { dataTransfer });
      }
    });
  });
});
