import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { mockStoreFactory, setMockStore, resetMockStore } from '../../test/mockStore';

vi.mock('../../store/useStore', () => mockStoreFactory());

// Import AFTER the mock is registered so the component picks up the mock.
const { MedicationManager } = await import('./MedicationManager');
const { useAuthStore } = await import('../../store/useStore');

const med = (overrides: Partial<Record<string, unknown>> = {}) => ({
  medication_id: 'm1',
  name: 'Ibuprofen',
  dosage: '200mg',
  frequency: 'daily',
  active: true,
  instructions: undefined,
  ...overrides,
});

const baseActions = {
  loadMedications: vi.fn(),
  createMedication: vi.fn(),
  updateMedication: vi.fn(),
  deleteMedication: vi.fn(),
  selectMedication: vi.fn(),
  clearError: vi.fn(),
  loadAdherence: vi.fn(),
  logDose: vi.fn(),
  isLoading: false,
  error: null,
  adherence: {},
  selectedMedication: null,
};

describe('MedicationManager', () => {
  beforeEach(() => {
    resetMockStore();
    setMockStore({
      useAuthStore: { user: { user_id: 'u1', username: 'tester' }, profile: {} },
    });
    baseActions.loadMedications.mockClear();
  });

  it('renders the medications from the store', () => {
    setMockStore({
      useMedicationStore: {
        ...baseActions,
        medications: [med({ name: 'Aspirin' }), med({ medication_id: 'm2', name: 'Warfarin' })],
      },
    });
    render(<MedicationManager />);
    expect(screen.getByText('Aspirin')).toBeInTheDocument();
    expect(screen.getByText('Warfarin')).toBeInTheDocument();
  });

  it('shows the empty state when there are no medications', () => {
    setMockStore({ useMedicationStore: { ...baseActions, medications: [] } });
    render(<MedicationManager />);
    expect(screen.getByText(/No medications yet/i)).toBeInTheDocument();
  });

  it('loads medications on mount', () => {
    setMockStore({ useMedicationStore: { ...baseActions, medications: [] } });
    render(<MedicationManager />);
    expect(baseActions.loadMedications).toHaveBeenCalled();
  });

  it('opens the create dialog when Add is clicked', () => {
    setMockStore({ useMedicationStore: { ...baseActions, medications: [] } });
    render(<MedicationManager />);
    fireEvent.click(screen.getByText('Add'));
    expect(screen.getByText('Add medication')).toBeInTheDocument();
  });

  it('renders an error banner when the store has an error', () => {
    setMockStore({
      useMedicationStore: { ...baseActions, medications: [], error: 'Something broke' },
    });
    render(<MedicationManager />);
    expect(screen.getByText('Something broke')).toBeInTheDocument();
  });
});
