import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import React from 'react';
import {
  SidebarSection,
  SidebarItem,
  SidebarDropdown,
  SidebarSubItem,
  SidebarDivider,
  SettingsSidebarSection,
  SettingsAccordionSection,
  SettingsSidebarItem,
} from '../SidebarComponents';
import { Home, Settings, Users, ChevronDown } from 'lucide-react';

const renderWithRouter = (component: React.ReactElement, initialPath = '/') => {
  return render(
    React.createElement(MemoryRouter, { initialEntries: [initialPath] }, component)
  );
};

describe('SidebarComponents', () => {
  describe('SidebarSection', () => {
    it('renders children', () => {
      render(
        React.createElement(SidebarSection, {}, 
          React.createElement('div', { 'data-testid': 'child' }, 'Child content')
        )
      );
      expect(screen.getByTestId('child')).toBeInTheDocument();
    });

    it('renders title when provided and not collapsed', () => {
      render(
        React.createElement(SidebarSection, { title: 'Test Section', isCollapsed: false },
          React.createElement('div', {}, 'Content')
        )
      );
      expect(screen.getByText('Test Section')).toBeInTheDocument();
    });

    it('hides title when collapsed', () => {
      render(
        React.createElement(SidebarSection, { title: 'Test Section', isCollapsed: true },
          React.createElement('div', {}, 'Content')
        )
      );
      expect(screen.queryByText('Test Section')).not.toBeInTheDocument();
    });

    it('shows divider when collapsed with title', () => {
      const { container } = render(
        React.createElement(SidebarSection, { title: 'Test', isCollapsed: true },
          React.createElement('div', {}, 'Content')
        )
      );
      expect(container.querySelector('.border-t')).toBeInTheDocument();
    });
  });

  describe('SidebarItem', () => {
    it('renders link with icon and label', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
        })
      );
      expect(screen.getByText('Dashboard')).toBeInTheDocument();
    });

    it('hides label when collapsed', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
          isCollapsed: true,
        })
      );
      expect(screen.queryByText('Dashboard')).not.toBeInTheDocument();
    });

    it('applies active styles when on matching path', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
        }),
        '/dashboard'
      );
      const link = screen.getByRole('link');
      expect(link).toHaveClass('bg-brand-text/10');
    });

    it('matches exactly when exact prop is true', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
          exact: true,
        }),
        '/dashboard/settings'
      );
      const link = screen.getByRole('link');
      expect(link).not.toHaveClass('bg-brand-text/10');
    });

    it('renders as disabled div when disabled', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
          disabled: true,
        })
      );
      expect(screen.queryByRole('link')).not.toBeInTheDocument();
      expect(screen.getByTitle('Dashboard')).toBeInTheDocument();
    });

    it('shows badge when provided', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
          badge: '5',
        })
      );
      expect(screen.getByText('5')).toBeInTheDocument();
    });

    it('shows badge element when provided', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
          badgeElement: React.createElement('span', { 'data-testid': 'custom-badge' }, 'New'),
        })
      );
      expect(screen.getByTestId('custom-badge')).toBeInTheDocument();
    });

    it('shows lock icon when locked', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/dashboard',
          icon: Home,
          label: 'Dashboard',
          locked: true,
        })
      );
      // Lock icon should be rendered
      expect(screen.getByRole('link')).toBeInTheDocument();
    });

    it('uses settings variant styling', () => {
      renderWithRouter(
        React.createElement(SidebarItem, {
          to: '/settings',
          icon: Settings,
          label: 'Settings',
          variant: 'settings',
        }),
        '/settings'
      );
      const link = screen.getByRole('link');
      expect(link).toHaveClass('bg-brand-50');
    });
  });

  describe('SidebarDropdown', () => {
    it('renders dropdown button with label', () => {
      renderWithRouter(
        React.createElement(SidebarDropdown, {
          icon: Users,
          label: 'Users',
          children: React.createElement('div', {}, 'Content'),
        })
      );
      expect(screen.getByText('Users')).toBeInTheDocument();
    });

    it('toggles content on click', () => {
      renderWithRouter(
        React.createElement(SidebarDropdown, {
          icon: Users,
          label: 'Users',
          children: React.createElement('div', { 'data-testid': 'dropdown-content' }, 'Content'),
        })
      );
      
      const button = screen.getByRole('button');
      fireEvent.click(button);
      
      expect(screen.getByTestId('dropdown-content')).toBeInTheDocument();
    });

    it('starts open when defaultOpen is true', () => {
      renderWithRouter(
        React.createElement(SidebarDropdown, {
          icon: Users,
          label: 'Users',
          defaultOpen: true,
          children: React.createElement('div', { 'data-testid': 'dropdown-content' }, 'Content'),
        })
      );
      expect(screen.getByTestId('dropdown-content')).toBeInTheDocument();
    });

    it('opens when path matches isActiveWhen', () => {
      renderWithRouter(
        React.createElement(SidebarDropdown, {
          icon: Users,
          label: 'Users',
          isActiveWhen: ['/users'],
          children: React.createElement('div', { 'data-testid': 'dropdown-content' }, 'Content'),
        }),
        '/users/list'
      );
      expect(screen.getByTestId('dropdown-content')).toBeInTheDocument();
    });

    it('hides content when collapsed', () => {
      renderWithRouter(
        React.createElement(SidebarDropdown, {
          icon: Users,
          label: 'Users',
          isCollapsed: true,
          defaultOpen: true,
          children: React.createElement('div', { 'data-testid': 'dropdown-content' }, 'Content'),
        })
      );
      expect(screen.queryByTestId('dropdown-content')).not.toBeInTheDocument();
    });
  });

  describe('SidebarSubItem', () => {
    it('renders sub-item link', () => {
      renderWithRouter(
        React.createElement(SidebarSubItem, {
          to: '/users/list',
          icon: Users,
          label: 'User List',
        })
      );
      expect(screen.getByText('User List')).toBeInTheDocument();
      expect(screen.getByRole('link')).toHaveAttribute('href', '/users/list');
    });

    it('applies active styles when on matching path', () => {
      renderWithRouter(
        React.createElement(SidebarSubItem, {
          to: '/users/list',
          icon: Users,
          label: 'User List',
        }),
        '/users/list'
      );
      const link = screen.getByRole('link');
      expect(link).toHaveClass('bg-brand-text/10');
    });
  });

  describe('SidebarDivider', () => {
    it('renders divider', () => {
      const { container } = render(React.createElement(SidebarDivider, {}));
      expect(container.querySelector('.border-t')).toBeInTheDocument();
    });

    it('applies collapsed styles', () => {
      const { container } = render(React.createElement(SidebarDivider, { isCollapsed: true }));
      expect(container.querySelector('.mx-3')).toBeInTheDocument();
    });

    it('applies expanded styles', () => {
      const { container } = render(React.createElement(SidebarDivider, { isCollapsed: false }));
      expect(container.querySelector('.mx-4')).toBeInTheDocument();
    });
  });

  describe('SettingsSidebarSection', () => {
    it('renders section with title and children', () => {
      render(
        React.createElement(SettingsSidebarSection, { title: 'General' },
          React.createElement('div', { 'data-testid': 'child' }, 'Content')
        )
      );
      expect(screen.getByText('General')).toBeInTheDocument();
      expect(screen.getByTestId('child')).toBeInTheDocument();
    });
  });

  describe('SettingsAccordionSection', () => {
    it('renders accordion section', () => {
      const onToggle = vi.fn();
      render(
        React.createElement(SettingsAccordionSection, {
          title: 'Advanced',
          sectionKey: 'advanced',
          isOpen: false,
          onToggle,
          children: React.createElement('div', { 'data-testid': 'content' }, 'Content'),
        })
      );
      expect(screen.getByText('Advanced')).toBeInTheDocument();
    });

    it('toggles on click', () => {
      const onToggle = vi.fn();
      render(
        React.createElement(SettingsAccordionSection, {
          title: 'Advanced',
          sectionKey: 'advanced',
          isOpen: false,
          onToggle,
          children: React.createElement('div', {}, 'Content'),
        })
      );
      
      fireEvent.click(screen.getByRole('button'));
      expect(onToggle).toHaveBeenCalledWith('advanced');
    });

    it('shows content when open', () => {
      render(
        React.createElement(SettingsAccordionSection, {
          title: 'Advanced',
          sectionKey: 'advanced',
          isOpen: true,
          onToggle: vi.fn(),
          children: React.createElement('div', { 'data-testid': 'content' }, 'Content'),
        })
      );
      expect(screen.getByTestId('content')).toBeInTheDocument();
    });

    it('does not render when hasVisibleItems is false', () => {
      const { container } = render(
        React.createElement(SettingsAccordionSection, {
          title: 'Advanced',
          sectionKey: 'advanced',
          isOpen: true,
          onToggle: vi.fn(),
          hasVisibleItems: false,
          children: React.createElement('div', {}, 'Content'),
        })
      );
      expect(container.firstChild).toBeNull();
    });
  });

  describe('SettingsSidebarItem', () => {
    it('renders settings item link', () => {
      renderWithRouter(
        React.createElement(SettingsSidebarItem, {
          to: '/settings/general',
          icon: Settings,
          label: 'General',
        })
      );
      expect(screen.getByText('General')).toBeInTheDocument();
    });

    it('renders description when provided', () => {
      renderWithRouter(
        React.createElement(SettingsSidebarItem, {
          to: '/settings/general',
          icon: Settings,
          label: 'General',
          description: 'Basic settings',
        })
      );
      expect(screen.getByText('Basic settings')).toBeInTheDocument();
    });

    it('shows lock icon when locked', () => {
      const { container } = renderWithRouter(
        React.createElement(SettingsSidebarItem, {
          to: '/settings/premium',
          icon: Settings,
          label: 'Premium',
          locked: true,
        })
      );
      // Lock component should be rendered
      expect(container.querySelector('svg')).toBeInTheDocument();
    });

    it('shows badge element when provided', () => {
      renderWithRouter(
        React.createElement(SettingsSidebarItem, {
          to: '/settings/beta',
          icon: Settings,
          label: 'Beta Feature',
          badgeElement: React.createElement('span', { 'data-testid': 'badge' }, 'Beta'),
        })
      );
      expect(screen.getByTestId('badge')).toBeInTheDocument();
    });

    it('applies active styles when on matching path', () => {
      renderWithRouter(
        React.createElement(SettingsSidebarItem, {
          to: '/settings/general',
          icon: Settings,
          label: 'General',
        }),
        '/settings/general'
      );
      const link = screen.getByRole('link');
      expect(link).toHaveClass('bg-brand-50');
    });
  });
});
