import React from 'react';
import {render, screen, waitFor} from '@testing-library/react';

const mockUseAuth = jest.fn();
jest.mock('@/contexts/AuthContext', () => ({
  useAuth: () => mockUseAuth(),
}));
jest.mock('next-intl', () => ({
  useTranslations: () => (key: string, values?: Record<string, unknown>) => `${key} ${values?.libelle}`,
  useLocale: () => 'fr',
}));
jest.mock('next/link', () => ({
  __esModule: true,
  default: ({children, href, ...props}: {children: React.ReactNode; href: string; [key: string]: unknown}) => (
    <a href={href} {...props}>{children}</a>
  ),
}));
jest.mock('@/services/favoriteService', () => ({
  getFavorites: jest.fn(),
  addApiFavorite: jest.fn(),
  removeApiFavorite: jest.fn(),
}));

import FavoriteButton from '../FavoriteButton';
import {getFavorites} from '@/services/favoriteService';

const mockedGetFavorites = getFavorites as jest.Mock;

describe('FavoriteButton', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('shouldShowAGreyedHeartAndALoginLinkWhenLoggedOut', () => {
    mockUseAuth.mockReturnValue({isAuthenticated: false, loading: false});

    render(<FavoriteButton cibleId={42} tableCible="annuaire_entree" libelle="Sylvain Barou" />);

    expect(screen.getByTestId('favorite-disabled')).toBeInTheDocument();
    const link = screen.getByRole('link', {name: 'favorite_login_link Sylvain Barou'});
    expect(link).toHaveAttribute('href', '/fr/connexion');
    expect(screen.queryByRole('button')).not.toBeInTheDocument();
  });

  it('shouldRenderNothingWhileTheAuthStateIsLoading', () => {
    mockUseAuth.mockReturnValue({isAuthenticated: false, loading: true});

    const {container} = render(<FavoriteButton cibleId={42} tableCible="annuaire_entree" libelle="Sylvain Barou" />);

    expect(container).toBeEmptyDOMElement();
  });

  it('shouldOfferTheFavoriteButtonWhenLoggedIn', async () => {
    mockUseAuth.mockReturnValue({isAuthenticated: true, loading: false});
    mockedGetFavorites.mockResolvedValue([]);

    render(<FavoriteButton cibleId={42} tableCible="annuaire_entree" libelle="Sylvain Barou" />);

    expect(screen.getByRole('button', {name: 'Add to favorites'})).toBeInTheDocument();
    expect(screen.queryByRole('link')).not.toBeInTheDocument();
    await waitFor(() => expect(mockedGetFavorites).toHaveBeenCalled());
  });
});
