import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react-native';
import DefaultStoreSelectorModal from '../DefaultStoreSelectorModalContainer';
import * as useDefaultStoreFilters from '../../../hooks/useDefaultStoreFilters';
import * as useSetPreSavedStores from '../../../hooks/useSetPreSavedStores';
import { bottomSheetHeaderAppliedFilters } from '../../../apollo/reactive-vars';
import { stores } from '../../MyCatalogBottomSheetFilter/constants';

jest.mock('../../../i18n', () => ({
    formatMessage: jest.fn(key => key),
    formatUpperCase: jest.fn(key => key),
    getCurrentLanguage: jest.fn(() => 'en')
}));

jest.mock('../../../branding', () => ({
    ...jest.requireActual('../../../branding'),
    useTheme: () => ({ colors: { midnight800: '#000', midnight600: '#111' } })
}));

// Stub the heavy gorhom-backed BottomSheet: expose its title and footer buttons,
// and drive each footer button with the live draft (as the real host does).
jest.mock('../../../componentsDS/BottomSheet', () => {
    /* eslint-disable @typescript-eslint/no-var-requires */
    const ReactMock = require('react');
    const { Text, TouchableOpacity } = require('react-native');
    const {
        bottomSheetHeaderAppliedFilters: draft
    } = require('../../../apollo/reactive-vars');
    const {
        bottomSheetScreen: screens
    } = require('../../../screens/MyCatalogScreen/BottomSheetFilter/constants');
    /* eslint-enable @typescript-eslint/no-var-requires */

    return {
        __esModule: true,
        default: ({
            title,
            isVisible,
            footerButtons,
            onClose
        }: {
            title: string;
            isVisible: boolean;
            footerButtons: {
                title: string;
                onPress: (
                    routeName: string,
                    currentScreenFilters: string[],
                    filters: Record<string, string[]>
                ) => void;
            }[];
            onClose: () => void;
        }) =>
            isVisible
                ? ReactMock.createElement(
                      ReactMock.Fragment,
                      null,
                      ReactMock.createElement(
                          Text,
                          { testID: 'sheet-title' },
                          title
                      ),
                      ...footerButtons.map(button =>
                          ReactMock.createElement(TouchableOpacity, {
                              key: button.title,
                              testID: `footer-${button.title}`,
                              onPress: () =>
                                  button.onPress(
                                      screens.stores,
                                      draft()[screens.stores] || [],
                                      draft()
                                  )
                          })
                      ),
                      ReactMock.createElement(TouchableOpacity, {
                          testID: 'sheet-close',
                          onPress: onClose
                      })
                  )
                : null
    };
});

describe('DefaultStoreSelectorModal', () => {
    const setStore = jest.fn();
    const onClose = jest.fn();
    const existingStore = stores[0];

    const renderSheet = ({
        isVisible = true,
        defaultStoreIds = [] as number[]
    } = {}) => {
        jest.spyOn(useDefaultStoreFilters, 'default').mockReturnValue({
            defaultStoreIds,
            loading: false
        });
        jest.spyOn(useSetPreSavedStores, 'default').mockReturnValue({
            setStore
        } as ReturnType<typeof useSetPreSavedStores.default>);

        return render(
            <DefaultStoreSelectorModal
                isVisible={isVisible}
                onClose={onClose}
            />
        );
    };

    beforeEach(() => {
        const i18n = jest.requireMock('../../../i18n');
        i18n.formatMessage.mockImplementation((key: string) => key);
        bottomSheetHeaderAppliedFilters({});
    });

    afterEach(jest.resetAllMocks);

    test('renders nothing while closed', () => {
        renderSheet({ isVisible: false });

        expect(screen.queryByTestId('sheet-title')).toBeNull();
    });

    test('shows the contextual STORE title with Clear and Apply actions', () => {
        renderSheet();

        expect(screen.getByTestId('sheet-title').props.children).toBe(
            'playlist.store'
        );
        expect(screen.getByTestId('footer-button.clear')).toBeTruthy();
        expect(screen.getByTestId('footer-filtering.apply')).toBeTruthy();
    });

    test('applies the saved default store and closes', () => {
        renderSheet({ defaultStoreIds: [existingStore.value] });

        fireEvent.press(screen.getByTestId('footer-filtering.apply'));

        expect(setStore).toHaveBeenCalledWith(existingStore.storeName);
        expect(onClose).toHaveBeenCalledTimes(1);
    });

    test('clearing the selection saves no store', () => {
        renderSheet({ defaultStoreIds: [existingStore.value] });

        fireEvent.press(screen.getByTestId('footer-button.clear'));
        fireEvent.press(screen.getByTestId('footer-filtering.apply'));

        expect(setStore).toHaveBeenCalledWith(undefined);
    });

    test('closing the sheet does not save', () => {
        renderSheet({ defaultStoreIds: [existingStore.value] });

        fireEvent.press(screen.getByTestId('sheet-close'));

        expect(onClose).toHaveBeenCalledTimes(1);
        expect(setStore).not.toHaveBeenCalled();
    });
});
