import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { ThemeProvider } from 'styled-components';
import AnalyticsPage from './Analytics';
import { AccountContext } from '../../contexts/AccountContext';
import { AuthContext } from '../../contexts/AuthContext';
import { Account } from '../../data';

const mockGet = jest.fn();

jest.mock('../../../axiosApi', () => ({
  axiosInstance: {
    get: (...args: unknown[]) => mockGet(...args),
    defaults: { headers: { common: {} as Record<string, string | null> } },
  },
  applyAccessToken: jest.fn(),
}));

jest.mock('../../components/ParticleBackground/ParticleBackground', () => () => null);
jest.mock('../../components/Header2/Header2', () => () => null);

beforeAll(() => {
  class ResizeObserverMock {
    observe() {}
    unobserve() {}
    disconnect() {}
  }
  (global as unknown as { ResizeObserver: typeof ResizeObserverMock }).ResizeObserver =
    ResizeObserverMock;
});

const theme = {
  main: '#4a90e2',
  focus: '#224466',
  darkMode: true,
  colors: {
    text: '#ffffff',
    cardBackground: 'rgba(0,0,0,0.3)',
    cardBorder: 'rgba(255,255,255,0.1)',
  },
};

const emptyHeatmap = {
  tz: 'UTC',
  total: 0,
  max: 0,
  days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  hours: Array.from({ length: 24 }, (_, i) => i),
  matrix: Array.from({ length: 7 }, () => Array(24).fill(0)),
  most_active_day: null,
  most_active_hour: null,
  peak_cell: null,
};

const renderPage = (accountInit?: ConstructorParameters<typeof Account>[0]) => {
  const account = new Account(accountInit || { email: 'user@example.com' });
  return render(
    <MemoryRouter>
      <ThemeProvider theme={theme as never}>
        <AuthContext.Provider
          value={{
            authenticated: true,
            setAuthentication: jest.fn(),
            needsNewPassword: false,
            setNeedsNewPassword: jest.fn(),
            loading: false,
          }}
        >
          <AccountContext.Provider value={{ account, setAccount: jest.fn() }}>
            <AnalyticsPage />
          </AccountContext.Provider>
        </AuthContext.Provider>
      </ThemeProvider>
    </MemoryRouter>
  );
};

describe('AnalyticsPage (#94)', () => {
  beforeEach(() => {
    mockGet.mockReset();
    mockGet.mockImplementation((url: string) => {
      if (url.includes('user_prompt_heatmap')) {
        return Promise.resolve({ data: emptyHeatmap });
      }
      return Promise.resolve({ data: [] });
    });
  });

  it('shows your activity section with heatmap for all users', async () => {
    renderPage();

    expect(await screen.findByText('Your activity')).toBeInTheDocument();
    expect(await screen.findByText('Prompt activity')).toBeInTheDocument();
    expect(screen.queryByText('Company')).not.toBeInTheDocument();
  });

  it('shows company section for company managers', async () => {
    renderPage({
      email: 'mgr@example.com',
      is_company_manager: true,
      company: { id: 1, name: 'Acme', state: '', zipcode: '', address: '' },
    });

    expect(await screen.findByText('Company')).toBeInTheDocument();
    await waitFor(() => {
      expect(screen.getByText('Team seat activity')).toBeInTheDocument();
    });
  });
});
