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  SystemLoginDetails from '../pages/ActivityReports/SystemLoginDetails.js';
import { UserProvider } from '../context/UserContext.js';
import { SystemLoginDetailsData } from '../mock-data/SystemLoginDetails.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: SystemLoginDetailsData,
            CurrentPage: 1,
            TotalPages: 3,
            TotalRecords: 102,
            PageSize: 50
        },
        columns: [
           { field: 'Total_Login_Time', headerName: 'Total Time', type: Number, flex: 2  },
          { field: 'LoginTime', headerName: 'Login Time', type: Date, flex: 2  },
          { field: 'LogoutTime', headerName: 'Logout Time', type: Date, flex: 2  },
          { field: 'SystemStatus', headerName: 'System Status', type: String, flex: 2.5 },
          { field: 'IpAddress', headerName: 'IP Address', type: String, flex: 2  },
          { field: 'ComputerName', headerName: 'Computer Name', type: String, flex: 2.5  },
          { field: 'AppVersion', headerName: 'App Version', type: String, 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}>
                <SystemLoginDetails {...defaultProps} {...props} />
            </UserProvider>
        </BrowserRouter>
    );
};



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

    beforeEach(() => {
        jest.clearAllMocks();
        mockPostApi.mockResolvedValue([
            { EmpCode: "EMP001", EmployeeName: "John Doe", LoginTime: "2024-01-01 08:00", LogoutTime: "2024-01-01 17: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();
    });

    // Tests to cover handleClear (lines 55-68)
    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 (shows after input has text)
        const clearButton = screen.getByTestId('search-clear-button');
        fireEvent.click(clearButton);
        
        await waitFor(() => {
            expect(screen.getByTestId('common-table')).toBeInTheDocument();
        });
    });

    // Tests to cover handleDateFilterChange (lines 72-84)
    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();
    });

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

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

    // Tests to cover getData error handling (line 48)
    it('handles API error gracefully', async () => {
        mockPostApi.mockRejectedValueOnce(new Error('API Error'));
        
        await act(async () => {
            expect(() => renderComponent()).not.toThrow();
        });
    }, 30000);

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

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

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

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