import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import ConversationCard from './ConversationCard';

jest.mock('../../ui-kit/components/MDTypography', () => ({
  __esModule: true,
  default: ({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) => (
    <button type="button" onClick={onClick}>
      {children}
    </button>
  ),
}));

const renderCard = (props: Partial<React.ComponentProps<typeof ConversationCard>> = {}) => {
  const setSelectConversation = props.setSelectConversation ?? jest.fn();
  const deleteConversation = props.deleteConversation ?? jest.fn();

  render(
    <ThemeProvider theme={createTheme()}>
      <ConversationCard
        title={props.title ?? 'My chat'}
        conversation_id={props.conversation_id ?? 5}
        setSelectConversation={setSelectConversation}
        deleteConversation={deleteConversation}
        selectedConversation={props.selectedConversation}
      />
    </ThemeProvider>
  );

  return { setSelectConversation, deleteConversation };
};

describe('ConversationCard', () => {
  it('renders conversation title', () => {
    renderCard({ title: 'Project brainstorm' });
    expect(screen.getByText('Project brainstorm')).toBeInTheDocument();
  });

  it('selects conversation when title clicked', async () => {
    const user = userEvent.setup();
    const { setSelectConversation } = renderCard({ conversation_id: 12 });

    await user.click(screen.getByText('My chat'));
    expect(setSelectConversation).toHaveBeenCalledWith(12);
  });

  it('deletes conversation when delete button clicked', async () => {
    const user = userEvent.setup();
    const { deleteConversation } = renderCard({ conversation_id: 8 });

    await user.click(screen.getByLabelText(/delete/i));
    expect(deleteConversation).toHaveBeenCalledWith(8);
  });
});
