import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider } from '../../theme';
import PatientCard from './PatientCard';
import type { Patient } from '@/services/patients/types';

const PATIENT: Patient = {
  id: 1,
  displayName: 'Zahra Mohammadi',
  firstName: 'Zahra',
  lastName: 'Mohammadi',
  birthDate: '1956-01-01',
  gender: 'female',
  bloodType: null,
  initialMedicalNotes: null,
  isActive: true,
  relation: 'parent',
  conditions: ['elderly'],
};

function renderCard(extra: { onOpen?: () => void; openLabel?: string } = {}) {
  const onEdit = jest.fn();
  const onArchive = jest.fn();
  render(
    <ThemeProvider>
      <PatientCard
        patient={PATIENT}
        relationLabel="Parent"
        genderLabel="Female"
        ageLabel="70 yrs"
        conditionLabels={['Elderly']}
        noConditionsLabel="No conditions"
        onEdit={onEdit}
        onArchive={onArchive}
        editLabel="Edit"
        archiveLabel="Archive"
        {...extra}
      />
    </ThemeProvider>,
  );
  return { onEdit, onArchive };
}

describe('<PatientCard/> component', () => {
  it('renders name, relation, meta and conditions', () => {
    renderCard();
    expect(screen.getByText('Zahra Mohammadi')).toBeInTheDocument();
    expect(screen.getByText('Parent')).toBeInTheDocument();
    expect(screen.getByText('70 yrs · Female')).toBeInTheDocument();
    expect(screen.getByText('Elderly')).toBeInTheDocument();
  });

  it('calls onEdit and onArchive from the action buttons', async () => {
    const user = userEvent.setup();
    const { onEdit, onArchive } = renderCard();
    await user.click(screen.getByLabelText('Edit'));
    await user.click(screen.getByLabelText('Archive'));
    expect(onEdit).toHaveBeenCalledTimes(1);
    expect(onArchive).toHaveBeenCalledTimes(1);
  });

  it('opens the record from the identity area without firing edit/archive', async () => {
    const user = userEvent.setup();
    const onOpen = jest.fn();
    const { onEdit, onArchive } = renderCard({ onOpen, openLabel: 'Open record' });
    await user.click(screen.getByLabelText('Open record'));
    expect(onOpen).toHaveBeenCalledTimes(1);
    expect(onEdit).not.toHaveBeenCalled();
    expect(onArchive).not.toHaveBeenCalled();
  });
});
