import React from 'react';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { jest } from "@jest/globals"
import  RunningApplicationDetails from '../pages/ActivityReports/RunningApplicationDetails.js';
import { runningApplicationMockData } from '../mock-data/RunningApplications.js';
import { UserProvider } from '../context/UserContext.js';

// Mock the apiService hook
const mockPostApi = jest.fn();
jest.unstable_mockModule("../services/apiService.js", () => ({
  default: () => ({
    postApi: mockPostApi,
  }),
}));

const mockUserContext = {
    permissions: [
        { Path: '/user-profile', Permission_Id: '1' },
    ],
};


const renderComponent = (props = {}) => {
    const defaultProps = {
        data: {
            Records: runningApplicationMockData,
            CurrentPage: 1,
            TotalPages: 3,
            TotalRecords: 102,
            PageSize: 50
        },
        columns: [
            { field: 'application_name', headerName: 'Application Name', type: String, flex: 2 },
            { field: 'application_count', headerName: 'Application Count', type: String, flex: 2 },
            { field: 'StartedOn', headerName: 'Started on', type: Date, flex: 2 },
            { field: 'browsing_time', headerName: 'Browsing Time', type: Number, flex: 2 },
        ],
        defaultSortColumn: '',
        onChange: jest.fn(),
        filters: { PageNumber: 1, PageSize: 10 },
        getUsersTable: jest.fn(),
        disableSorting: false,
        title: 'Test Table',
        isAutoHeight: true,
        handleModifyPermissions: jest.fn()
    };

    return render(
        <BrowserRouter>
            <UserProvider value={mockUserContext}>
                <RunningApplicationDetails {...defaultProps} {...props} />
            </UserProvider>
        </BrowserRouter>
    );
};



describe('RunningApplicationDetails Component', () => {

    beforeEach(() => {
        jest.clearAllMocks();
        mockPostApi.mockResolvedValue([
            { emp_code: "EMP001", application_name: "Chrome", application_count: 5, browsing_time: "01:30:00" }
        ]);
    });

    it('renders component with default state', async () => {
        renderComponent()
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    it('shows loader while data is fetching', async () => {
        renderComponent();
        expect(screen.getByTestId('loader')).toBeInTheDocument();
    });

    it('renders userProfile specific columns', async () => {
        renderComponent({ title: "userProfile" });
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    it('renders employee columns for default case', async () => {
        renderComponent();
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    it('handles search input', async () => {
        renderComponent();
        const searchInput = screen.getByTestId('search-input-field');
        expect(searchInput).toBeInTheDocument();
    });

    it('renders SmartDateSelector component', async () => {
        renderComponent();
        const dateFilter = screen.getByRole('combobox', { name: 'Date Filter' });
        expect(dateFilter).toBeInTheDocument();
        fireEvent.mouseDown(dateFilter);
    });

    it('renders CommonTable component', async () => {
        renderComponent();
        const dateFilter = screen.getByRole('combobox', { name: 'Date Filter' });
        expect(dateFilter).toBeInTheDocument();
    });

    it('renders with employeeId prop', () => {
        renderComponent({ employeeId: 'EMP001' });
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    it('does not render search input when employeeId provided', () => {
        const { container } = renderComponent({ employeeId: 'EMP001' });
        const searchInputs = container.querySelectorAll('input[placeholder*="Search"]');
        expect(searchInputs.length).toBe(0);
    });

    it('renders inner-container', () => {
        const { container } = renderComponent();
        expect(container.querySelector('.inner-container')).toBeInTheDocument();
    });

    it('renders filters-wrapper', () => {
        const { container } = renderComponent();
        expect(container.querySelector('.filters-wrapper')).toBeInTheDocument();
    });

    it('handles date filter change', async () => {
        renderComponent();
        const dateFilter = screen.getByRole('combobox', { name: 'Date Filter' });
        fireEvent.mouseDown(dateFilter);
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
    });

    it('renders with EmployeeName prop', () => {
        renderComponent({ EmployeeName: 'John Doe' });
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    it('renders with summaryFilter prop', () => {
        const summaryFilter = {
            EmpCode: 'EMP001',
            CallDate: { startDate: '2024-01-01', endDate: '2024-01-31' },
            ResultsFor: 'day'
        };
        renderComponent({ summaryFilter });
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    it('renders other-filters section', () => {
        const { container } = renderComponent();
        expect(container.querySelector('.other-filters')).toBeInTheDocument();
    });

    // Additional tests to cover more lines

    // Test handleClear (lines 61-73)
    it('handleClear resets filters and fetches data', async () => {
        renderComponent();
        
        const searchInput = screen.getByRole('textbox');
        fireEvent.change(searchInput, { target: { value: 'test search' } });
        
        await waitFor(() => {
            expect(searchInput.value).toBe('test search');
        });
        
        // Find and click clear button
        const clearButton = screen.getByTestId('search-clear-button');
        fireEvent.click(clearButton);
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
    });

    // Test handleDateFilterChange (lines 77-92)
    it('handleDateFilterChange updates filters with date range', async () => {
        renderComponent();
        
        const dateFilter = screen.getByRole('combobox', { name: 'Date Filter' });
        fireEvent.mouseDown(dateFilter);
        
        await waitFor(() => {
            const options = screen.getAllByRole('option');
            if (options.length > 0) {
                fireEvent.click(options[0]);
            }
        });
        
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    // Test handleSearch (lines 97-114)
    it('handleSearch triggers data fetch with search text', async () => {
        renderComponent();
        
        const searchInput = screen.getByRole('textbox');
        fireEvent.change(searchInput, { target: { value: 'chrome' } });
        
        const searchButton = screen.getByTestId('search-button');
        fireEvent.click(searchButton);
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
    });

    // Test API error handling (line 49)
    it('handles API error gracefully', async () => {
        mockPostApi.mockRejectedValueOnce(new Error('API Error'));
        const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
        
        await act(async () => {
            renderComponent();
        });
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
        
        consoleSpy.mockRestore();
    }, 10000);

    // Test null result from API
    it('handles null result from API', async () => {
        mockPostApi.mockResolvedValueOnce(null);
        
        await act(async () => {
            renderComponent();
        });
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
    });

    // Test togglePopup (lines 151-152)
    it('togglePopup shows and hides popup', async () => {
        await act(async () => {
            renderComponent();
        });
        
        // The popup functionality is tested through CommonTable interaction
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    // Test with title other than userProfile
    it('renders with default title', () => {
        renderComponent({ title: 'dashboard' });
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    // Test handleSearch with lowercase conversion
    it('handleSearch converts search text to lowercase', async () => {
        renderComponent();
        
        const searchInput = screen.getByRole('textbox');
        fireEvent.change(searchInput, { target: { value: 'CHROME' } });
        
        const searchButton = screen.getByTestId('search-button');
        fireEvent.click(searchButton);
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
    });

    // Test with numeric employeeId
    it('renders with numeric employeeId', () => {
        renderComponent({ employeeId: 12345 });
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    // Test handleDateFilterChange with EmployeeName
    it('handleDateFilterChange uses EmployeeName when available', async () => {
        renderComponent({ EmployeeName: 'John Doe' });
        
        const dateFilter = screen.getByRole('combobox', { name: 'Date Filter' });
        fireEvent.mouseDown(dateFilter);
        
        await waitFor(() => {
            const options = screen.getAllByRole('option');
            if (options.length > 0) {
                fireEvent.click(options[0]);
            }
        });
        
        expect(screen.getByTestId('common-table')).toBeInTheDocument();
    });

    // Test handleClear with EmployeeName prop
    it('handleClear uses EmployeeName prop', async () => {
        renderComponent({ EmployeeName: 'John Doe' });
        
        const searchInput = screen.getByRole('textbox');
        fireEvent.change(searchInput, { target: { value: 'test' } });
        
        await waitFor(() => {
            expect(searchInput.value).toBe('test');
        });
        
        const clearButton = screen.getByTestId('search-clear-button');
        fireEvent.click(clearButton);
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
    });
});