import React from 'react';

import { fireEvent } from '@testing-library/react-native';

import { render } from '@/components/testUtils';
import Card, { CardProps } from '@/components/shared/Card';
import { Text } from 'react-native';
import { theme } from '@/app/shared/theme';

type RenderCardProps = Omit<CardProps, 'children'> & { children?: React.ReactNode };

const renderComponent = ({ backgroundColor, onPress, children = 'content'}: RenderCardProps) => {
  const base = render(
    <Card backgroundColor={backgroundColor} onPress={onPress} testID='card'>
      <Text>{children}</Text>
    </Card>
  );

  return base;
};

describe('[Component] Card', () => {
  test('renders correctly', () => {
    const card = renderComponent({ backgroundColor: 'red' });

    expect(card).toMatchSnapshot();
  });

  test('renders children correctly', () => {
    const { getByText } = renderComponent({ backgroundColor: 'red', children: 'Test Content'});

    expect(getByText('Test Content')).toBeTruthy();
  });

  test('applies the correct background color', () => {
    const { getByTestId } = renderComponent({ backgroundColor: 'green'});

    const card = getByTestId('card');
    expect(card?.props.style[0].backgroundColor).toEqual(theme.colors.fixed.green);
  });

  test('does not render as TouchableOpacity when onPress is not provided', () => {
    const { queryByTestId } = renderComponent({ backgroundColor: 'red' });

    // TouchableOpacity should not exist
    expect(queryByTestId('card').props.onPress).toBeUndefined();
  });

  test('handles undefined onPress gracefully when pressed', () => {
    // Ce test vérifie que le comportement est correct quand onPress est undefined
    const { getByTestId } = renderComponent({
      backgroundColor: 'red',
      onPress: undefined,
      children: 'Press me safely'
    });

    // Vérifie qu'aucune erreur n'est levée lors de l'appui
    expect(() => {
      fireEvent.press(getByTestId('card'));
    }).not.toThrow();
  });

  test('calls onPress when pressed', () => {
    const onPressMock = jest.fn();
    const { getByTestId } = renderComponent({
      backgroundColor: 'green',
      onPress: onPressMock,
      children: 'Press me'
    });

    fireEvent.press(getByTestId('card'));
    expect(onPressMock).toHaveBeenCalled();
  });
});
