import { mockToolkitActionCreator } from 'test/core/redux/mocks';
import { render, screen } from 'test/test-utils';

import { type NavModel } from '@grafana/data';
import { ModalRoot } from '@grafana/ui';
import { type Organization } from 'app/types/organization';

import { backendSrv } from '../../core/services/backend_srv';

import { OrgDetailsPage, type Props } from './OrgDetailsPage';
import { setOrganizationName } from './state/reducers';

jest.mock('app/core/services/context_srv', () => {
  return {
    contextSrv: {
      ...jest.requireActual('app/core/services/context_srv').contextSrv,
      hasPermission: () => true,
    },
  };
});

const setup = (propOverrides?: object) => {
  jest.clearAllMocks();
  // needed because SharedPreferences is rendered in the test
  jest.spyOn(backendSrv, 'put');
  jest
    .spyOn(backendSrv, 'get')
    .mockResolvedValue({ timezone: 'UTC', homeDashboardUID: 'home-dashboard', theme: 'dark' });
  jest.spyOn(backendSrv, 'search').mockResolvedValue([]);

  const props: Props = {
    organization: {} as Organization,
    navModel: {
      main: {
        text: 'Configuration',
      },
      node: {
        text: 'Org details',
      },
    } as NavModel,
    loadOrganization: jest.fn(),
    setOrganizationName: mockToolkitActionCreator(setOrganizationName),
    updateOrganization: jest.fn(),
  };
  Object.assign(props, propOverrides);

  return render(
    <>
      <OrgDetailsPage {...props} />
      <ModalRoot />
    </>
  );
};

jest.mock('app/features/dashboard/api/dashboard_api', () => ({
  getDashboardAPI: () => ({
    getDashboardDTO: jest.fn().mockResolvedValue({}),
  }),
}));

describe('Render', () => {
  beforeEach(() => {
    jest.spyOn(console, 'error').mockImplementation(() => {});
  });

  it('should render component', () => {
    expect(() => setup()).not.toThrow();
  });

  it('should render organization and preferences', () => {
    expect(() =>
      setup({
        organization: {
          name: 'Cool org',
          id: 1,
        },
        preferences: {
          homeDashboardUID: 'home-dashboard',
          theme: 'Default',
          timezone: 'Default',
          locale: '',
        },
      })
    ).not.toThrow();
  });

  it('should show a modal when submitting', async () => {
    const { user } = setup({
      organization: {
        name: 'Cool org',
        id: 1,
      },
      preferences: {
        homeDashboardUID: 'home-dashboard',
        theme: 'Default',
        timezone: 'Default',
        locale: '',
      },
    });

    await user.click(screen.getByRole('button', { name: 'Save preferences' }));

    expect(await screen.findByText('Confirm preferences update')).toBeInTheDocument();
  });
});
