import React from 'react';
import { render, waitFor } from '@testing-library/react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { i18n } from '@/app/i18n/i18n'; // Assure-toi que ce chemin est correct
import { LanguageProvider, LanguageContext } from '../LanguageProvider';

jest.mock('@react-native-async-storage/async-storage', () => ({
  getItem: jest.fn(),
  setItem: jest.fn(),
}));

jest.mock('@/app/i18n/i18n', () => ({
  i18n: {
    localI18n: {
      locale: 'fr',
    },
  },
}));

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

  test('should initialize with default language as "fr" if no language is stored', async () => {
    AsyncStorage.getItem.mockResolvedValueOnce(null);

    const { getByText } = render(
      <LanguageProvider>
        <LanguageContext.Consumer>
          {({ userChangeLanguage }) => (
            <>{i18n.localI18n.locale}</> // Affiche la langue courante
          )}
        </LanguageContext.Consumer>
      </LanguageProvider>
    );

    await waitFor(() => {
      expect(i18n.localI18n.locale).toBe('fr');
    });
  });

  test('should load stored language from AsyncStorage if available', async () => {
    AsyncStorage.getItem.mockResolvedValueOnce('en');

    const { getByText } = render(
      <LanguageProvider>
        <LanguageContext.Consumer>
          {({ userChangeLanguage }) => (
            <>{i18n.localI18n.locale}</>
          )}
        </LanguageContext.Consumer>
      </LanguageProvider>
    );

    await waitFor(() => {
      expect(i18n.localI18n.locale).toBe('en');
    });
  });

  test('should allow user to change language and save it to AsyncStorage', async () => {
    AsyncStorage.getItem.mockResolvedValueOnce(null);

    const { getByTestId } = render(
      <LanguageProvider>
        <LanguageContext.Consumer>
          {({ userChangeLanguage }) => (
            <>
              <>{i18n.localI18n.locale}</> {/* Affiche la langue courante */}
              <button
                onPress={() => userChangeLanguage('en')}
                testID="change-language-button"
              >
                Change to English
              </button>
            </>
          )}
        </LanguageContext.Consumer>
      </LanguageProvider>
    );

    const button = getByTestId('change-language-button');
    button.props.onPress();

    await waitFor(() => {
      expect(i18n.localI18n.locale).toBe('en');
      expect(AsyncStorage.setItem).toHaveBeenCalledWith('storedLanguage', 'en');
    });
  });
});
