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);
});

// Intercepts the Blob passed to URL.createObjectURL during handleExport so tests
// can inspect the actual CSV text produced, rather than inferring it from the
// <select>'s DOM value (which can be misleading — see the coercion test below).
// Also stubs anchor .click() — jsdom treats a real click on an <a href="blob:...">
// as a navigation attempt, which it doesn't implement; that throws asynchronously
// (after the test has moved on) and can flakily fail an unrelated later test.
function mockDownload() {
  let blob = null;
  const origCreate = global.URL.createObjectURL;
  const origRevoke = global.URL.revokeObjectURL;
  const origClick = window.HTMLAnchorElement.prototype.click;
  global.URL.createObjectURL = jest.fn((b) => { blob = b; return 'blob:mock'; });
  global.URL.revokeObjectURL = jest.fn();
  window.HTMLAnchorElement.prototype.click = jest.fn();
  return {
    getBlob: () => blob,
    // handleExport schedules `setTimeout(() => URL.revokeObjectURL(url), 0)`; flush
    // that pending macrotask before unmocking, or it fires after restore() has put
    // back the (non-existent, in jsdom) original revokeObjectURL and throws async —
    // an error jest attributes to whatever test happens to run next.
    restore: async () => {
      await new Promise((r) => setTimeout(r, 0));
      global.URL.createObjectURL = origCreate;
      global.URL.revokeObjectURL = origRevoke;
      window.HTMLAnchorElement.prototype.click = origClick;
    },
  };
}

function readBlobText(blob) {
  return new Promise((resolve, reject) => {
    const fr = new FileReader();
    fr.onload = () => resolve(fr.result);
    fr.onerror = reject;
    fr.readAsText(blob);
  });
}

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'));
  });

  it('defaults Group by to None when groupField is __none__, and the exported CSV has no Group row (Issue-1 regression guard: default export reproduces today\'s export)', async () => {
    const dl = mockDownload();
    renderModal({ groupField: '__none__' });
    await screen.findByLabelText('Rows');
    expect(screen.getByLabelText('Group by')).toHaveValue('__none__');
    await waitFor(() => expect(screen.getByText(/1 date/i)).toBeInTheDocument());
    fireEvent.click(screen.getByText('Export CSV'));
    const text = await readBlobText(dl.getBlob());
    expect(text).not.toMatch(/^Group,/m);
    await dl.restore();
  });

  it('defaults Group by to the saved field when it is a valid active subject field', async () => {
    renderModal({ groupField: 'grp' });
    await screen.findByLabelText('Rows');
    expect(screen.getByLabelText('Group by')).toHaveValue('grp');
  });

  it('coerces Group by to None when the saved field no longer exists in subjectTemplate, so the export carries no stray Group row (Issue-2 guard)', async () => {
    // Note: asserting the <select>'s DOM .value here would be misleading — React's
    // controlled <select> falls back to selecting the first <option> ("__none__")
    // whenever the given value matches no option, regardless of whether the
    // component actually validated/coerced its internal state. So we assert the
    // real behavioral effect (the exported CSV) instead.
    const dl = mockDownload();
    renderModal({ groupField: 'ghost-field' });
    await screen.findByLabelText('Rows');
    await waitFor(() => expect(screen.getByText(/1 date/i)).toBeInTheDocument());
    fireEvent.click(screen.getByText('Export CSV'));
    const text = await readBlobText(dl.getBlob());
    expect(text).not.toMatch(/^Group,/m);
    await dl.restore();
  });
});
