import React from 'react';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import ExportDataModal from '../src/components/ExportDataModal';
import * as client from '../src/api/client';

jest.mock('../src/api/client', () => ({
  experimentsApi: { getDailyStatuses: jest.fn() },
}));

const animals = [
  { id: 'a1', animal_name: 'Alpha', animal_id_string: 'R-001', subject_info: { grp: 'Control' } },
  { id: 'a2', animal_name: 'Beta', animal_id_string: 'R-002', subject_info: { grp: 'Drug' } },
];
const statuses = [
  { animal_id: 'a1', date: '2026-07-01T00:00:00.000Z', analysis_summary: { total: 5 } },
  { animal_id: 'a2', date: '2026-07-01T00:00:00.000Z', analysis_summary: { total: 9 } },
];
const subjectTemplate = [{ fieldId: 'grp', label: 'Group', active: true }];

beforeEach(() => {
  jest.clearAllMocks();
  client.experimentsApi.getDailyStatuses.mockResolvedValue(statuses);
});

function renderModal(props = {}) {
  return render(
    <ExportDataModal
      experimentId="exp-1"
      experimentTitle="My Study"
      dailyTemplate={[]}
      animals={animals}
      subjectTemplate={subjectTemplate}
      groupField="__none__"
      onClose={jest.fn()}
      {...props}
    />,
  );
}

describe('ExportDataModal', () => {
  it('defaults to Rows=Date, Columns=Subject and shows the preview', async () => {
    renderModal();
    expect(await screen.findByLabelText('Rows')).toHaveValue('date');
    expect(screen.getByLabelText('Columns')).toHaveValue('subject');
    await waitFor(() => expect(screen.getByText(/1 date.*2 subjects/i)).toBeInTheDocument());
  });

  it('hides the Group by control until Subject is an axis', async () => {
    renderModal();
    await screen.findByLabelText('Rows');
    // subject is a column by default -> Group by visible
    expect(screen.getByLabelText('Group by')).toBeInTheDocument();
    // move subject off both axes: Rows=Date, Columns=Parameter -> subject pinned
    fireEvent.change(screen.getByLabelText('Columns'), { target: { value: 'parameter' } });
    await waitFor(() => expect(screen.queryByLabelText('Group by')).not.toBeInTheDocument());
  });

  it('keeps row and column dimensions distinct', async () => {
    renderModal();
    const rows = await screen.findByLabelText('Rows');
    fireEvent.change(rows, { target: { value: 'subject' } }); // collides with column=subject
    await waitFor(() => expect(screen.getByLabelText('Columns')).not.toHaveValue('subject'));
  });
});
